

write.csv(zsm_pccc,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zsm_pccc.csv")


#as of 02/08/22 - this is the most current, most bells-and-whistles version of the graph. outstanding issues are to add a dotted line of the SWE 2021-no-heatwave scenario, and to add the daily temperature dot to the legend, which is currently all lines
#this has been tweaked from the 12/27/21 version to add annotate boxes for all three heatwaves, change their color to grey, and draw on the PRISM temps vs the Stampede Pass station data. One shortcoming of this is that the PRISM data that is "stable" only extends through July currently. On 3/1 I can add the August temps and that should be all the PRISM temps needed.
zsm_pCasccClean = read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zsm_pCasccClean.csv",header=T)
#parse out just the melt curves
zsm_pccc = subset(zsm_pCasccClean,zsm_pCasccClean$Curve=="DEC")

PWmt <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\ZS_PRISM_PersW66.csv",header=T)

PWmt21 = subset(PWmt,WY==2021)
#PWmt$mod_TA3MA <- (StmPs$TempAnom3DMA*(-0.0125)) + 1.075
#unused right now
PWmt21$mod_TM3MA <- (PWmt21$Mean3MA*(-0.03)) + 1.33
PWmt21$mod_TM5MA <- (PWmt21$Mean5MA*(-0.03)) + 1.33
PWmt21$mod_NAT <- (PWmt21$NormC9120OfficialPDXTransPersW66*(-0.03)) + 1.33


library(ggplot2)
ttlsnm = labs(title= "SWE and mean temperature over the melting season", x="Day of the Water Year",y="Proportion of annual maximum SWE")

#no longer used text in the plot:
# annotate("rect",xmin=282.5,xmax=287.5,ymin=0,ymax=1.33,alpha=0.15,fill="grey10")+
#    annotate("rect",xmin=301.5,xmax=302.5,ymin=0,ymax=1.33,alpha=0.15,fill="grey10")+
#    annotate("rect",xmin=302.5,xmax=304.5,ymin=0,ymax=1.33,alpha=0.25,fill="grey10")+

dswetmpf <-
ggplot() + 
    annotate("rect",xmin=197.5,xmax=198.5,ymin=.5,ymax=1.33,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=198.5,xmax=201.5,ymin=.5,ymax=1.33,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=201.5,xmax=203.5,ymin=.5,ymax=1.33,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=225.5,xmax=229.5,ymin=0,ymax=1.33,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=242.5,xmax=243.5,ymin=0,ymax=1.33,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=243.5,xmax=247.5,ymin=0,ymax=1.33,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=262.5,xmax=263.5,ymin=0,ymax=1.33,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=263.5,xmax=269.5,ymin=0,ymax=1.33,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=269.5,xmax=273.5,ymin=0,ymax=1.33,alpha=0.5,fill="grey10")+
    annotate("rect",xmin=273.5,xmax=275.5,ymin=0,ymax=1.33,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=275.5,xmax=280.5,ymin=0,ymax=1.33,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=307,xmax=310,ymin=1.13,ymax=1.21,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=307,xmax=310,ymin=1.05,ymax=1.13,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=307,xmax=310,ymin=0.97,ymax=1.05,alpha=0.5,fill="grey10")+
    annotate("text",x=310.5,y=1.14,label="+3-5\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=310.5,y=1.06,label="+5-10\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=310.5,y=0.98,label="+10\u00b0C anomaly\n(Heat Dome)",size=3,hjust=0,vjust=0)+
    geom_line(data=PWmt21,aes(x=DoWY,y=mod_TM3MA,linetype="2021 daily mean \n(3-day moving average)"),color="tomato3") +
    geom_point(data=PWmt21,aes(x=DoWY,y=mod_TM3MA),color="tomato3",size=0.9) +
    geom_line(data=PWmt21,aes(x=DoWY,y=mod_NAT,linetype="Historic mean"),color="tomato3") +
    geom_line(data=subset(zsm_pccc,zsm_pccc$ENSOType=="Neutral"),aes(x=DoWY,y=NPMean,group=WY,color="ENSO neutral years"),alpha=0.75)+
    geom_line(data=subset(zsm_pccc,zsm_pccc$ENSOType=="LaNina"),aes(x=DoWY,y=NPMean,group=WY,color="La Ni\u00f1a years"),alpha=0.75)+
    geom_line(data=subset(zsm_pccc,zsm_pccc$ENSOType=="ElNino"),aes(x=DoWY,y=NPMean,group=WY,color="El Ni\u00f1o years"),alpha=0.75)+
    geom_line(data=subset(zsm_pccc,zsm_pccc$WY==2011),aes(x=DoWY,y=NPMean,color="2011 (Strong La Ni\u00f1a)"))+
    geom_line(data=subset(zsm_pccc,zsm_pccc$WY==2021), aes(x=DoWY,y=NPMean,color="2021"))+
    geom_hline(aes(yintercept=1.33),alpha=0.25) +
    annotate("text",x=c(167,198,228,259,289,320),y=c(-.02,-.02,-.02,-.02,-.02,-.02),label=c("March","April","May","June","July","August"))+
    scale_x_continuous(limits=c(152,336),breaks=c(152,183,213,244,274,305,336),expand=c(0,5))+
    scale_y_continuous(limits=c(-0.05,1.5),breaks=seq(0,1,0.1),expand=c(0,0),sec.axis=sec_axis(~ ((.)-1.33)/-0.03,name="Temperature (\u00b0C)",breaks=seq(-5,35,5))) + ttlsnm + 
    scale_colour_manual(name="Daily SWE (normalized)",values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO Neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) +
    scale_linetype_manual(name="Temperatures",values=c("2021 daily mean \n(3-day moving average)"=1,"Historic mean"=2),guide=guide_legend(override.aes=list(linetype=c(1,2),color="tomato3")))+
    theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,1,0,0),"mm")),axis.title.y.right=element_text(margin=unit(c(0,0,0,2.5),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),legend.position=c(0.17,0.25),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),panel.border = element_rect(colour = "black", fill=NA, size=2))



sum6dev <- c(47.476852,16.881614,56.068122,20.006614,47.546296,40.651455,0,0,29.69246,41.468254,31.074735,81.977513,132.592593,48.779762,67.222222,42.400794,45.684524,114.917328)
nd1pt8 <- c(11,21,11,12,14,19,12,9,6,13,15,31,24,22,20,19,11,18)
ENSO <- c(0,0.5,-0.5,0.5,-1.5,-0.5,1,-1.5,-1,0,0,0.5,2,-0.5,-0.5,0.5,0,-1)
testsum6 = ggplot()+
geom_point(aes(x=sum6dev,y=nd1pt8,color=factor(ENSO)),size=2)+ 
scale_color_brewer(palette="RdBu",direction=-1)

### 030922 - Figure 3b relating 3MA temp anomaly to 3MA SWE loss % ###

TmpMltA <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\TempMeltScatterFigure.csv",header=T)
#load master csv for this figure

library(ggplot2)
library(RColorBrewer)
#load graphing libraries
#update this figure to include the geom_smooth aspect. make sure the plot includes the heat dome points for calculating the line. 
tmpmlt21f <- 
ggplot(data=subset(TmpMltA,WY==2021),aes(x=AnomC9120OfficialPDXTransPersW663MA,y=PercentMelt3MA,color=DayType))+
     geom_point(size=3) + 
     geom_smooth(data=subset(TmpMltA,WY==2021),aes(x=AnomC9120OfficialPDXTransPersW663MA,y=PercentMelt3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)+
     scale_color_manual(values=c("red","black"))+ 
     labs(title= "SWE percent loss relationship to\ndaily temperature anomaly", x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)")+
     scale_y_continuous(limits=c(-3,0.5),breaks=seq(-3,0.5,0.5)) +
     scale_x_continuous(limits=c(-8,18),breaks=seq(-5,15,5)) +
     theme(panel.background=element_blank(), axis.text.x=element_text(face="bold",size=14),axis.text.y=element_text(face="bold",size=14),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,2,0,0),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),
     legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "grey30"),
     legend.position=c(0.75,0.85),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),legend.text=element_text(size=12),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
#as of 031822, this is the polished version of the figure
summary(lm(data=as.data.frame(pia5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=subset(TmpMltA,WY==2021),PercentMelt3MA~AnomC9120OfficialPDXTransPersW663MA))

#061223 - quick check of the regression assumptions of the above
par(mfrow = c(2, 2))
plot(lm(data=as.data.frame(pia5Csince93),DegDayPlus5C_30~Year))
library(lmtest)
dwtest(lm(data=as.data.frame(pia5Csince93),DegDayPlus5C_30~Year))
library(car)
ncvTest(lm(data=as.data.frame(pia5Csince93),DegDayPlus5C_30~Year))
#seems like there is non-constant variance. ie heteroscedastic. The lm_robust tools seems appropriate.
library(estimatr)
summary(lm_robust(data=as.data.frame(pia5Csince93),DegDayPlus5C_30~Year,se_type="HC3"))
#very cool, totally works, and the slopes are unaffected

#checking whether the robust differ from the standard lm
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1938:2021){
      SA5CDDrsq.30x[i-1937] <- summary(lm_robust(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1937] <- summary(lm_robust(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2],se_type="HC3"))$coefficients[8]
      SA5CDDs.30x[i-1937] <- summary(lm_robust(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2],se_type="HC3"))$coefficients[2]
      }

##03/11/21 Figure 4 updated
library(scales)
#for not clipping the out of bounds (oob) confidence interval in the plot
library(colorspace)
#for manually centering the color scale

DegDayPlus5C_A = vector()
DegDayPlus5C_30 = vector()
DayCountPlus5C_A = vector()
DayCountPlus5C_30 = vector()


for(i in 1938:2021){
      DegDayPlus5C_A[i-1937] <- sum(subset(subset(subset(pdxall,Month==4|Month==5|Month==6),Year==i),DevFromNormAll>9)$DevFromNormAll)
      DegDayPlus5C_30[i-1937] <- sum(subset(subset(subset(pdxall,Month==4|Month==5|Month==6),Year==i),DevFromNorm9120>9)$DevFromNorm9120)
      DayCountPlus5C_A[i-1937] <- nrow(subset(subset(subset(pdxall,Month==4|Month==5|Month==6),Year==i),DevFromNormAll>9))
      DayCountPlus5C_30[i-1937] <- nrow(subset(subset(subset(pdxall,Month==4|Month==5|Month==6),Year==i),DevFromNorm9120>9))
      }

pdx5Cbyyr = data.frame(Year=seq(1938,2021), DegDayPlus5C_A, DegDayPlus5C_30, DayCountPlus5C_A, DayCountPlus5C_30)
pdx5Cbyyr$DegExpOver5C_A <- pdx5Cbyyr$DegDayPlus5C_A - (9*DayCountPlus5C_A)
pdx5Cbyyr$DegExpOver5C_30 <- pdx5Cbyyr$DegDayPlus5C_30 - (9*DayCountPlus5C_30)
pdx5Cbyyr$ENSO <- pdxbyyr$ENSO

##repeating analysis for a different station - Paradise Ranger Station, which goes back until December 1916
prsall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\ParadiseRSHistoricalDaily1621.csv",header=T)

PRSDegDayPlus5C_30 = vector()
PRSDayCountPlus5C_30 = vector()
PRSNACount = vector()

for(i in 1917:2021){
      PRSDegDayPlus5C_30[i-1916] <- sum(subset(subset(subset(prsall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      PRSDayCountPlus5C_30[i-1916] <- nrow(subset(subset(subset(prsall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      PRSNACount[i-1916] <- sum(is.na(subset(subset(prsall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

prs5Cbyyr = data.frame(Year=seq(1917,2021), PRSDegDayPlus5C_30, PRSDayCountPlus5C_30)
prs5Cbyyr$PRSDegExpOver5C_30 <- prs5Cbyyr$PRSDegDayPlus5C_30 - (5*PRSDayCountPlus5C_30)
PRS5Cbyyr$PRSDegDayPlus5C_30_noNA <- ifelse(PRSNACount<5,PRSDegDayPlus5C_30,NA)

ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#repeating it again for another station at lower, but still medium (842m?), elevation
lmrall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\LongmireNPSHistoricalDaily0921.csv",header=T)

LmrDegDayPlus5C_30 = vector()
LmrDayCountPlus5C_30 = vector()
LmrNACount = vector()

for(i in 1909:2021){
      LmrDegDayPlus5C_30[i-1908] <- sum(subset(subset(subset(lmrall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      LmrDayCountPlus5C_30[i-1908] <- nrow(subset(subset(subset(lmrall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      LmrNACount[i-1908] <- sum(is.na(subset(subset(lmrall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

lmr5Cbyyr = data.frame(Year=seq(1909,2021), LmrDegDayPlus5C_30, LmrDayCountPlus5C_30)
lmr5Cbyyr$LmrDegExpOver5C_30 <- lmr5Cbyyr$LmrDegDayPlus5C_30 - (5*LmrDayCountPlus5C_30)
lmr5Cbyyr$LmrDegDayPlus5C_30_noNA <- ifelse(LmrNACount<5,LmrDegDayPlus5C_30,NA)

ggplot(lmr5Cbyyr,aes(x=Year,y=LmrDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(lmr5Cbyyr,aes(x=Year,y=LmrDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(lmr5Cbyyr,aes(x=Year,y=LmrDegExpOver5C_30,label=Year),na.rm=F) + geom_point()
ggplot(lmr5Cbyyr,aes(x=Year,y=LmrDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()

#another station, Mt Adams Ranger Station
mtaall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\MtAdamsRSHistoricalDaily2421.csv",header=T)

MtADegDayPlus5C_30 = vector()
MtADayCountPlus5C_30 = vector()
MtANACount = vector()

for(i in 1925:2021){
      MtADegDayPlus5C_30[i-1924] <- sum(subset(subset(subset(mtaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      MtADayCountPlus5C_30[i-1924] <- nrow(subset(subset(subset(mtaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      MtANACount[i-1924] <- sum(is.na(subset(subset(mtaall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

mta5Cbyyr = data.frame(Year=seq(1925,2021), MtADegDayPlus5C_30, MtADayCountPlus5C_30)
mta5Cbyyr$MtADegExpOver5C_30 <- mta5Cbyyr$MtADegDayPlus5C_30 - (5*MtADayCountPlus5C_30)
mta5Cbyyr$MtADegDayPlus5C_30_noNA <- ifelse(MtANACount<5,MtADegDayPlus5C_30,NA)

ggplot(mta5Cbyyr,aes(x=Year,y=MtADegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mta5Cbyyr,aes(x=Year,y=MtADegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()

#another low elevation station, this one in Bellingham
biaall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\BellinghamIntlAirportHistoricalDaily4921.csv",header=T)

BIADegDayPlus5C_30 = vector()
BIADayCountPlus5C_30 = vector()
BIANACount = vector()

for(i in 1949:2021){
      BIADegDayPlus5C_30[i-1948] <- sum(subset(subset(subset(biaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      BIADayCountPlus5C_30[i-1948] <- nrow(subset(subset(subset(biaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      BIANACount[i-1948] <- sum(is.na(subset(subset(biaall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

bia5Cbyyr = data.frame(Year=seq(1949,2021), BIADegDayPlus5C_30, BIADayCountPlus5C_30)
bia5Cbyyr$BIADegExpOver5C_30 <- bia5Cbyyr$BIADegDayPlus5C_30 - (5*BIADayCountPlus5C_30)
bia5Cbyyr$BIADegDayPlus5C_30_noNA <- ifelse(BIANACount<5,BIADegDayPlus5C_30,NA)

ggplot(bia5Cbyyr,aes(x=Year,y=BIADegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(bia5Cbyyr,aes(x=Year,y=BIADegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#another station - Bonneville Dam
bnvall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\BonnevilleDamHistoricalDaily3721.csv",header=T)

BnvDegDayPlus5C_30 = vector()
BnvDayCountPlus5C_30 = vector()
BnvNACount = vector()

for(i in 1938:2021){
      BnvDegDayPlus5C_30[i-1937] <- sum(subset(subset(subset(bnvall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      BnvDayCountPlus5C_30[i-1937] <- nrow(subset(subset(subset(bnvall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      BnvNACount[i-1937] <- sum(is.na(subset(subset(bnvall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

bnv5Cbyyr = data.frame(Year=seq(1938,2021), BnvDegDayPlus5C_30, BnvDayCountPlus5C_30)
bnv5Cbyyr$BnvDegExpOver5C_30 <- bnv5Cbyyr$BnvDegDayPlus5C_30 - (5*BnvDayCountPlus5C_30)
bnv5Cbyyr$BnvDegDayPlus5C_30_noNA <- ifelse(BnvNACount<5,BnvDegDayPlus5C_30,NA)

ggplot(bnv5Cbyyr,aes(x=Year,y=BnvDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(bnv5Cbyyr,aes(x=Year,y=BnvDegExpOver5C_30,label=Year),na.rm=F) + geom_point()    

#another station - Olympia AP
oapall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\OlympiaAirportHistoricalDaily4121.csv",header=T)

OAPDegDayPlus5C_30 = vector()
OAPDayCountPlus5C_30 = vector()
OAPNACount = vector()

for(i in 1942:2021){
      OAPDegDayPlus5C_30[i-1941] <- sum(subset(subset(subset(oapall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      OAPDayCountPlus5C_30[i-1941] <- nrow(subset(subset(subset(oapall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      OAPNACount[i-1941] <- sum(is.na(subset(subset(oapall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

oap5Cbyyr = data.frame(Year=seq(1942,2021), OAPDegDayPlus5C_30, OAPDayCountPlus5C_30)
oap5Cbyyr$OAPDegExpOver5C_30 <- oap5Cbyyr$OAPDegDayPlus5C_30 - (5*OAPDayCountPlus5C_30)
oap5Cbyyr$OAPDegDayPlus5C_30_noNA <- ifelse(OAPNACount<5,OAPDegDayPlus5C_30,NA)

ggplot(oap5Cbyyr,aes(x=Year,y=OAPDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(oap5Cbyyr,aes(x=Year,y=OAPDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#another station - McKenzie River Ranger Station (near Eugene) - can't use this one, it's missing a ton of dates including like all of 2011 June
mckall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\McKenzieRiverRSHistoricalDaily0221.csv",header=T)

McKDegDayPlus5C_30 = vector()
McKDayCountPlus5C_30 = vector()
McKNACount = vector()

for(i in 1902:2021){
      McKDegDayPlus5C_30[i-1901] <- sum(subset(subset(subset(mckall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      McKDayCountPlus5C_30[i-1901] <- nrow(subset(subset(subset(mckall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      McKNACount[i-1901] <- sum(is.na(subset(subset(mckall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

mck5Cbyyr = data.frame(Year=seq(1902,2021), McKDegDayPlus5C_30, McKDayCountPlus5C_30)

mck5Cbyyr$McKDegExpOver5C_30 <- mck5Cbyyr$McKDegDayPlus5C_30 - (5*McKDayCountPlus5C_30)
mck5Cbyyr$McKDegDayPlus5C_30_noNA <- ifelse(McKNACount<5,McKDegDayPlus5C_30,NA)

ggplot(mck5Cbyyr,aes(x=Year,y=McKDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mck5Cbyyr,aes(x=Year,y=McKDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(mck5Cbyyr,aes(x=Year,y=McKDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#111722 - revisiting station plots to put a few in supplemental
#do Prospect2SW (1940-2021), McKenzie River (1945-2021), Government Camp (1952-2021), Paradise RS (1940-2021), Forks1E (1946-2021)
                         
#station - Crater Lake
crlall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\CraterLakeNPSHQHistoricalDaily2021.csv",header=T)

CrLDegDayPlus5C_30 = vector()
CrLDayCountPlus5C_30 = vector()
CrLNACount = vector()

for(i in 1920:2021){
      CrLDegDayPlus5C_30[i-1919] <- sum(subset(subset(subset(crlall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      CrLDayCountPlus5C_30[i-1919] <- nrow(subset(subset(subset(crlall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      CrLNACount[i-1919] <- sum(is.na(subset(subset(crlall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

crl5Cbyyr = data.frame(Year=seq(1920,2021), CrLDegDayPlus5C_30, CrLDayCountPlus5C_30)

crl5Cbyyr$CrLDegExpOver5C_30 <- crl5Cbyyr$CrLDegDayPlus5C_30 - (5*CrLDayCountPlus5C_30)
crl5Cbyyr$CrLDegDayPlus5C_30_noNA <- ifelse(CrLNACount<5,CrLDegDayPlus5C_30,NA)

ggplot(crl5Cbyyr,aes(x=Year,y=CrLDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(crl5Cbyyr,aes(x=Year,y=CrLDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(crl5Cbyyr,aes(x=Year,y=CrLDegExpOver5C_30,label=Year),na.rm=F) + geom_point()
#looks good, code works. Find 3-5 stations to do this way, from different taus and elevations

#station - Government Camps
gvcall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\GovernmentCampHistoricalDaily5221.csv",header=T)

GvCDegDayPlus5C_30 = vector()
GvCDayCountPlus5C_30 = vector()
GvCNACount = vector()
for(i in 1952:2021){
      GvCDegDayPlus5C_30[i-1951] <- sum(subset(subset(subset(gvcall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      GvCDayCountPlus5C_30[i-1951] <- nrow(subset(subset(subset(gvcall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      GvCNACount[i-1951] <- sum(is.na(subset(subset(gvcall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

gvc5Cbyyr = data.frame(Year=seq(1952,2021), GvCDegDayPlus5C_30, GvCDayCountPlus5C_30)
gvc5Cbyyr$GvCDegExpOver5C_30 <- gvc5Cbyyr$GvCDegDayPlus5C_30 - (5*GvCDayCountPlus5C_30)
gvc5Cbyyr$GvCDegDayPlus5C_30_noNA <- ifelse(GvCNACount<5,GvCDegDayPlus5C_30,NA)

ggplot(gvc5Cbyyr,aes(x=Year,y=GvCDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(gvc5Cbyyr,aes(x=Year,y=GvCDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(gvc5Cbyyr,aes(x=Year,y=GvCDegExpOver5C_30,label=Year),na.rm=F) + geom_point()
#looks good, code works. Find 3-5 stations to do this way, from different taus and elevations

#station - Prospect 2 SW station, just SW of Crater Lake - can't do this one because it has so many missing values in recent decades
p2sall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\Prospect2SWHistoricalDaily0521.csv",header=T)

p2sDegDayPlus5C_30 = vector()
p2sDayCountPlus5C_30 = vector()
p2sNACount = vector()

for(i in 1906:2021){
      p2sDegDayPlus5C_30[i-1905] <- sum(subset(subset(subset(p2sall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      p2sDayCountPlus5C_30[i-1905] <- nrow(subset(subset(subset(p2sall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      p2sNACount[i-1905] <- sum(is.na(subset(subset(p2sall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

p2s5Cbyyr = data.frame(Year=seq(1906,2021), p2sDegDayPlus5C_30, p2sDayCountPlus5C_30)

p2s5Cbyyr$p2sDegExpOver5C_30 <- p2s5Cbyyr$p2sDegDayPlus5C_30 - (5*p2sDayCountPlus5C_30)
p2s5Cbyyr$p2sDegDayPlus5C_30_noNA <- ifelse(p2sNACount<5,p2sDegDayPlus5C_30,NA)

ggplot(p2s5Cbyyr,aes(x=Year,y=p2sDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(p2s5Cbyyr,aes(x=Year,y=p2sDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(p2s5Cbyyr,aes(x=Year,y=p2sDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(p2s5Cbyyr,aes(x=Year,y=p2sDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Forks 1 E station, NE shore of Mt Olympus
f1eall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\Forks1EHistoricalDaily0821.csv",header=T)

f1eDegDayPlus5C_30 = vector()
f1eDayCountPlus5C_30 = vector()
f1eNACount = vector()

for(i in 1908:2021){
      f1eDegDayPlus5C_30[i-1907] <- sum(subset(subset(subset(f1eall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      f1eDayCountPlus5C_30[i-1907] <- nrow(subset(subset(subset(f1eall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      f1eNACount[i-1907] <- sum(is.na(subset(subset(f1eall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

f1e5Cbyyr = data.frame(Year=seq(1908,2021), f1eDegDayPlus5C_30, f1eDayCountPlus5C_30)

f1e5Cbyyr$f1eDegExpOver5C_30 <- f1e5Cbyyr$f1eDegDayPlus5C_30 - (5*f1eDayCountPlus5C_30)
f1e5Cbyyr$f1eDegDayPlus5C_30_noNA <- ifelse(f1eNACount<5,f1eDegDayPlus5C_30,NA)

ggplot(f1e5Cbyyr,aes(x=Year,y=f1eDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(f1e5Cbyyr,aes(x=Year,y=f1eDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(f1e5Cbyyr,aes(x=Year,y=f1eDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Sisters, OR
sisall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\SistersHistoricalDaily5921.csv",header=T)

sisDegDayPlus5C_30 = vector()
sisDayCountPlus5C_30 = vector()
sisNACount = vector()

for(i in 1959:2021){
      sisDegDayPlus5C_30[i-1958] <- sum(subset(subset(subset(sisall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      sisDayCountPlus5C_30[i-1958] <- nrow(subset(subset(subset(sisall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      sisNACount[i-1958] <- sum(is.na(subset(subset(sisall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

sis5Cbyyr = data.frame(Year=seq(1959,2021), sisDegDayPlus5C_30, sisDayCountPlus5C_30)

sis5Cbyyr$sisDegExpOver5C_30 <- sis5Cbyyr$sisDegDayPlus5C_30 - (5*sisDayCountPlus5C_30)
sis5Cbyyr$sisDegDayPlus5C_30_noNA <- ifelse(sisNACount<5,sisDegDayPlus5C_30,NA)

ggplot(sis5Cbyyr,aes(x=Year,y=sisDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(sis5Cbyyr,aes(x=Year,y=sisDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(sis5Cbyyr,aes(x=Year,y=sisDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(sis5Cbyyr,aes(x=Year,y=sisDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Santiam Junction
sjcall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\SantiamJunctionHistoricalDaily5021.csv",header=T)

sjcDegDayPlus5C_30 = vector()
sjcDayCountPlus5C_30 = vector()
sjcNACount = vector()

for(i in 1950:2021){
      sjcDegDayPlus5C_30[i-1949] <- sum(subset(subset(subset(sjcall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      sjcDayCountPlus5C_30[i-1949] <- nrow(subset(subset(subset(sjcall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      sjcNACount[i-1949] <- sum(is.na(subset(subset(sjcall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

sjc5Cbyyr = data.frame(Year=seq(1950,2021), sjcDegDayPlus5C_30, sjcDayCountPlus5C_30)

sjc5Cbyyr$sjcDegExpOver5C_30 <- sjc5Cbyyr$sjcDegDayPlus5C_30 - (5*sjcDayCountPlus5C_30)
sjc5Cbyyr$sjcDegDayPlus5C_30_noNA <- ifelse(sjcNACount<5,sjcDegDayPlus5C_30,NA)

ggplot(sjc5Cbyyr,aes(x=Year,y=sjcDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(sjc5Cbyyr,aes(x=Year,y=sjcDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(sjc5Cbyyr,aes(x=Year,y=sjcDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(sjc5Cbyyr,aes(x=Year,y=sjcDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Grants Pass
gtpall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\GrantsPassHistoricalDaily9321.csv",header=T)

gtpDegDayPlus5C_30 = vector()
gtpDayCountPlus5C_30 = vector()
gtpNACount = vector()

for(i in 1893:2021){
      gtpDegDayPlus5C_30[i-1892] <- sum(subset(subset(subset(gtpall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      gtpDayCountPlus5C_30[i-1892] <- nrow(subset(subset(subset(gtpall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      gtpNACount[i-1892] <- sum(is.na(subset(subset(gtpall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

gtp5Cbyyr = data.frame(Year=seq(1893,2021), gtpDegDayPlus5C_30, gtpDayCountPlus5C_30)

gtp5Cbyyr$gtpDegExpOver5C_30 <- gtp5Cbyyr$gtpDegDayPlus5C_30 - (5*gtpDayCountPlus5C_30)
gtp5Cbyyr$gtpDegDayPlus5C_30_noNA <- ifelse(gtpNACount<5,gtpDegDayPlus5C_30,NA)

ggplot(gtp5Cbyyr,aes(x=Year,y=gtpDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(gtp5Cbyyr,aes(x=Year,y=gtpDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(gtp5Cbyyr,aes(x=Year,y=gtpDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(gtp5Cbyyr,aes(x=Year,y=gtpDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Wikiup Dam, OR
wkdall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\WikiupDamHistoricalDaily4221.csv",header=T)

wkdDegDayPlus5C_30 = vector()
wkdDayCountPlus5C_30 = vector()
wkdNACount = vector()

for(i in 1942:2021){
      wkdDegDayPlus5C_30[i-1941] <- sum(subset(subset(subset(wkdall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      wkdDayCountPlus5C_30[i-1941] <- nrow(subset(subset(subset(wkdall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      wkdNACount[i-1941] <- sum(is.na(subset(subset(wkdall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

wkd5Cbyyr = data.frame(Year=seq(1942,2021), wkdDegDayPlus5C_30, wkdDayCountPlus5C_30)

wkd5Cbyyr$wkdDegExpOver5C_30 <- wkd5Cbyyr$wkdDegDayPlus5C_30 - (5*wkdDayCountPlus5C_30)
wkd5Cbyyr$wkdDegDayPlus5C_30_noNA <- ifelse(wkdNACount<5,wkdDegDayPlus5C_30,NA)

ggplot(wkd5Cbyyr,aes(x=Year,y=wkdDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(wkd5Cbyyr,aes(x=Year,y=wkdDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(wkd5Cbyyr,aes(x=Year,y=wkdDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(wkd5Cbyyr,aes(x=Year,y=wkdDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Tulelake, CA - trash, is missing lots of recent years
tulall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\TulelakeHistoricalDaily3221.csv",header=T)

tulDegDayPlus5C_30 = vector()
tulDayCountPlus5C_30 = vector()
tulNACount = vector()

for(i in 1932:2021){
      tulDegDayPlus5C_30[i-1931] <- sum(subset(subset(subset(tulall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      tulDayCountPlus5C_30[i-1931] <- nrow(subset(subset(subset(tulall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      tulNACount[i-1931] <- sum(is.na(subset(subset(tulall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

tul5Cbyyr = data.frame(Year=seq(1932,2021), tulDegDayPlus5C_30, tulDayCountPlus5C_30)

tul5Cbyyr$tulDegExpOver5C_30 <- tul5Cbyyr$tulDegDayPlus5C_30 - (5*tulDayCountPlus5C_30)
tul5Cbyyr$tulDegDayPlus5C_30_noNA <- ifelse(tulNACount<5,tulDegDayPlus5C_30,NA)

ggplot(tul5Cbyyr,aes(x=Year,y=tulDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(tul5Cbyyr,aes(x=Year,y=tulDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(tul5Cbyyr,aes(x=Year,y=tulDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(tul5Cbyyr,aes(x=Year,y=tulDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Ashland, OR - 
ashall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\AshlandHistoricalDaily9321.csv",header=T)

ashDegDayPlus5C_30 = vector()
ashDayCountPlus5C_30 = vector()
ashNACount = vector()

for(i in 1893:2021){
      ashDegDayPlus5C_30[i-1892] <- sum(subset(subset(subset(ashall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      ashDayCountPlus5C_30[i-1892] <- nrow(subset(subset(subset(ashall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      ashNACount[i-1892] <- sum(is.na(subset(subset(ashall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

ash5Cbyyr = data.frame(Year=seq(1893,2021), ashDegDayPlus5C_30, ashDayCountPlus5C_30)

ash5Cbyyr$ashDegExpOver5C_30 <- ash5Cbyyr$ashDegDayPlus5C_30 - (5*ashDayCountPlus5C_30)
ash5Cbyyr$ashDegDayPlus5C_30_noNA <- ifelse(ashNACount<5,ashDegDayPlus5C_30,NA)

ggplot(ash5Cbyyr,aes(x=Year,y=ashDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(ash5Cbyyr,aes(x=Year,y=ashDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(ash5Cbyyr,aes(x=Year,y=ashDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(ash5Cbyyr,aes(x=Year,y=ashDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Medford International Airport, OR - 
miaall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\MedfordInternationalAirportHistoricalDaily1121.csv",header=T)

miaDegDayPlus5C_30 = vector()
miaDayCountPlus5C_30 = vector()
miaNACount = vector()

for(i in 1911:2021){
      miaDegDayPlus5C_30[i-1910] <- sum(subset(subset(subset(miaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      miaDayCountPlus5C_30[i-1910] <- nrow(subset(subset(subset(miaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      miaNACount[i-1910] <- sum(is.na(subset(subset(miaall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

mia5Cbyyr = data.frame(Year=seq(1911,2021), miaDegDayPlus5C_30, miaDayCountPlus5C_30)

mia5Cbyyr$miaDegExpOver5C_30 <- mia5Cbyyr$miaDegDayPlus5C_30 - (5*miaDayCountPlus5C_30)
mia5Cbyyr$miaDegDayPlus5C_30_noNA <- ifelse(miaNACount<5,miaDegDayPlus5C_30,NA)

ggplot(mia5Cbyyr,aes(x=Year,y=miaDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mia5Cbyyr,aes(x=Year,y=miaDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(mia5Cbyyr,aes(x=Year,y=miaDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mia5Cbyyr,aes(x=Year,y=miaDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Mud Mountain Dam, WA - 
mmdall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\MudMountainDamHistoricalDaily3921.csv",header=T)

mmdDegDayPlus5C_30 = vector()
mmdDayCountPlus5C_30 = vector()
mmdNACount = vector()

for(i in 1939:2021){
      mmdDegDayPlus5C_30[i-1938] <- sum(subset(subset(subset(mmdall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      mmdDayCountPlus5C_30[i-1938] <- nrow(subset(subset(subset(mmdall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      mmdNACount[i-1938] <- sum(is.na(subset(subset(mmdall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

mmd5Cbyyr = data.frame(Year=seq(1939,2021), mmdDegDayPlus5C_30, mmdDayCountPlus5C_30)

mmd5Cbyyr$mmdDegExpOver5C_30 <- mmd5Cbyyr$mmdDegDayPlus5C_30 - (5*mmdDayCountPlus5C_30)
mmd5Cbyyr$mmdDegDayPlus5C_30_noNA <- ifelse(mmdNACount<5,mmdDegDayPlus5C_30,NA)

ggplot(mmd5Cbyyr,aes(x=Year,y=mmdDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mmd5Cbyyr,aes(x=Year,y=mmdDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(mmd5Cbyyr,aes(x=Year,y=mmdDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mmd5Cbyyr,aes(x=Year,y=mmdDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Palmer 3 ESE, WA - 
p3eall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\Palmer3ESEHistoricalDaily2521.csv",header=T)

p3eDegDayPlus5C_30 = vector()
p3eDayCountPlus5C_30 = vector()
p3eNACount = vector()

for(i in 1925:2021){
      p3eDegDayPlus5C_30[i-1924] <- sum(subset(subset(subset(p3eall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      p3eDayCountPlus5C_30[i-1924] <- nrow(subset(subset(subset(p3eall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      p3eNACount[i-1924] <- sum(is.na(subset(subset(p3eall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

p3e5Cbyyr = data.frame(Year=seq(1925,2021), p3eDegDayPlus5C_30, p3eDayCountPlus5C_30)

p3e5Cbyyr$p3eDegExpOver5C_30 <- p3e5Cbyyr$p3eDegDayPlus5C_30 - (5*p3eDayCountPlus5C_30)
p3e5Cbyyr$p3eDegDayPlus5C_30_noNA <- ifelse(p3eNACount<5,p3eDegDayPlus5C_30,NA)

ggplot(p3e5Cbyyr,aes(x=Year,y=p3eDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(p3e5Cbyyr,aes(x=Year,y=p3eDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(p3e5Cbyyr,aes(x=Year,y=p3eDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(p3e5Cbyyr,aes(x=Year,y=p3eDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#station - Marion Forks Fish Hatchery, ORDDD - 
mfhall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\MarionForksFishHatcheryHistoricalDaily4921.csv",header=T)

mfhDegDayPlus5C_30 = vector()
mfhDayCountPlus5C_30 = vector()
mfhNACount = vector()

for(i in 1949:2021){
      mfhDegDayPlus5C_30[i-1948] <- sum(subset(subset(subset(mfhall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      mfhDayCountPlus5C_30[i-1948] <- nrow(subset(subset(subset(mfhall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      mfhNACount[i-1948] <- sum(is.na(subset(subset(mfhall,Month==4|Month==5|Month==6),Year==i)$AnomTempC))
      }

mfh5Cbyyr = data.frame(Year=seq(1949,2021), mfhDegDayPlus5C_30, mfhDayCountPlus5C_30)

mfh5Cbyyr$mfhDegExpOver5C_30 <- mfh5Cbyyr$mfhDegDayPlus5C_30 - (5*mfhDayCountPlus5C_30)
mfh5Cbyyr$mfhDegDayPlus5C_30_noNA <- ifelse(mfhNACount<5,mfhDegDayPlus5C_30,NA)

ggplot(mfh5Cbyyr,aes(x=Year,y=mfhDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mfh5Cbyyr,aes(x=Year,y=mfhDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
ggplot(mfh5Cbyyr,aes(x=Year,y=mfhDayCountPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(mfh5Cbyyr,aes(x=Year,y=mfhDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

#111822. making plots for supplemental of a few stations. 1100x420 pixels? (x450 for earlier paradise version, x420 for PDX in main body)
#112622 - settled on 4 plots for supplemental: from North - South:
# Forks 1 E (1908), Mud Mountain Dam (1939), Wikiup Dam (1942), Medford Int'l Airport (1911)
#set all to 1940-2021, regardless of record.
#do 1940-21 for Forks1E f1e, , WikiupDam wkd
Prospect2SW (1940-2021), McKenzie River (1945-2021), Government Camp (1952-2021), Paradise RS (1940-2021), Forks1E (1946-2021)

#manually paste in ENSO for 1917 onwards for all the 5 datasets below (except prs which already has it, and is where the ENSO data is being pasted from)
write.csv(f1e5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\f1e5Cbyyr.csv")
write.csv(gvc5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\gvc5Cbyyr.csv")
write.csv(mck5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\mck5Cbyyr.csv")
write.csv(p2s5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\p2s5Cbyyr.csv")
write.csv(mmd5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\mmd5Cbyyr.csv")
write.csv(wkd5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\wkd5Cbyyr.csv")
write.csv(mia5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\mia5Cbyyr.csv")

#read in pre-existing PRS dataset
prs5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\prs5Cbyyr.csv",header=T)
prs5Cbyyr$ENSO[100] <- 2
#THIS ADJUSTS THE 2.5 TO 2 for 2016 ENSO. this needs to be done or else it throws off the scale (it is the only 2.5)
f1e5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\f1e5Cbyyr.csv",header=T)
f1e5Cbyyr$ENSO[109] <- 2

gvc5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\gvc5Cbyyr.csv",header=T)
gvc5Cbyyr$ENSO[65] <- 2

mck5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\mck5Cbyyr.csv",header=T)
mck5Cbyyr$ENSO[115] <- 2

p2s5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\p2s5Cbyyr.csv",header=T)
p2s5Cbyyr$ENSO[111] <- 2

mmd5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\mmd5Cbyyr.csv",header=T)
mmd5Cbyyr$ENSO[78] <- 2

wkd5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\wkd5Cbyyr.csv",header=T)
wkd5Cbyyr$ENSO[75] <- 2

mia5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\mia5Cbyyr.csv",header=T)
mia5Cbyyr$ENSO[106] <- 2

#define dataset since 1993 for geom_smooth
f1e5Csince93 <- cbind("Year"=f1e5Cbyyr[(nrow(f1e5Cbyyr)-28):nrow(f1e5Cbyyr),1],"DegDayPlus5C_30"=f1e5Cbyyr[(nrow(f1e5Cbyyr)-28):nrow(f1e5Cbyyr),6])
prs5Csince93 <- cbind("Year"=prs5Cbyyr[(nrow(prs5Cbyyr)-28):nrow(prs5Cbyyr),1],"DegDayPlus5C_30"=prs5Cbyyr[(nrow(prs5Cbyyr)-28):nrow(prs5Cbyyr),6])
gvc5Csince93 <- cbind("Year"=gvc5Cbyyr[(nrow(gvc5Cbyyr)-28):nrow(gvc5Cbyyr),1],"DegDayPlus5C_30"=gvc5Cbyyr[(nrow(gvc5Cbyyr)-28):nrow(gvc5Cbyyr),6])
mck5Csince93 <- cbind("Year"=mck5Cbyyr[(nrow(mck5Cbyyr)-28):nrow(mck5Cbyyr),1],"DegDayPlus5C_30"=mck5Cbyyr[(nrow(mck5Cbyyr)-28):nrow(mck5Cbyyr),6])
p2s5Csince93 <- cbind("Year"=p2s5Cbyyr[(nrow(p2s5Cbyyr)-28):nrow(p2s5Cbyyr),1],"DegDayPlus5C_30"=p2s5Cbyyr[(nrow(p2s5Cbyyr)-28):nrow(p2s5Cbyyr),6])
mmd5Csince93 <- cbind("Year"=mmd5Cbyyr[(nrow(mmd5Cbyyr)-28):nrow(mmd5Cbyyr),1],"DegDayPlus5C_30"=mmd5Cbyyr[(nrow(mmd5Cbyyr)-28):nrow(mmd5Cbyyr),5])
wkd5Csince93 <- cbind("Year"=wkd5Cbyyr[(nrow(wkd5Cbyyr)-28):nrow(wkd5Cbyyr),1],"DegDayPlus5C_30"=wkd5Cbyyr[(nrow(wkd5Cbyyr)-28):nrow(wkd5Cbyyr),5])
mia5Csince93 <- cbind("Year"=mia5Cbyyr[(nrow(mia5Cbyyr)-28):nrow(mia5Cbyyr),1],"DegDayPlus5C_30"=mia5Cbyyr[(nrow(mia5Cbyyr)-28):nrow(mia5Cbyyr),5])

#info for caption on the slopes of the smoothed figures
summary(lm(data=as.data.frame(f1e5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=as.data.frame(prs5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=as.data.frame(gvc5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=as.data.frame(mck5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=as.data.frame(p2s5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=as.data.frame(mmd5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=as.data.frame(wkd5Csince93),DegDayPlus5C_30~Year))
summary(lm(data=as.data.frame(mia5Csince93),DegDayPlus5C_30~Year))

#adjust line like this to do quick look and figure out how to set text and limits
ggplot(f1e5Cbyyr,aes(x=Year,y=f1eDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-120, >50
ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-275, >150
ggplot(gvc5Cbyyr,aes(x=Year,y=GvCDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-260, >125
ggplot(mck5Cbyyr,aes(x=Year,y=McKDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-175, >100
ggplot(p2s5Cbyyr,aes(x=Year,y=p2sDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-150, >75
ggplot(mmd5Cbyyr,aes(x=Year,y=mmdDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-200, >74
ggplot(wkd5Cbyyr,aes(x=Year,y=wkdDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-207, >100
ggplot(mia5Cbyyr,aes(x=Year,y=miaDegDayPlus5C_30_noNA,label=Year),na.rm=F) + geom_point()
#0-175, >99

#making 4 plots: f1e, mmd, wkd, mia -  original thought to do PRS and p2s scrapped b/s they are missing too many dates
#this version of the graph looks great at 1000x415. No further changes to f1eDegDayPlus5CAnoms
# earlier versions exported 1100x420 - actually, try 900x350 for all of these, so you can fit 5 per a page at 1.8 height
#112622 - perfect, all plots will use these axes, but year labels will adjust. 950x415 size?
#used same axes for all plots (1940-2021, 0-210), only adjusted the labels for unusually high years, exported to 900x400 into a pdf where I manually overlapped the images as I wanted, saved as a png, then pasted into the manuscript as a single image that I also cropped to be the right size for 1 page.
f1eDegDayPlus5Canoms = ggplot(f1e5Cbyyr,aes(x=Year,y=f1eDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(f1e5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text_repel(aes(label=ifelse(f1eDegDayPlus5C_30>50,as.character(Year),'')),hjust=0.8,vjust=1,nudge_y=22,nudge_x=-3,size=3.5,segment.colour=NA)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(a) USC00452914: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
f1eDegDayPlus5Canoms

#112622 - perfect, all plots will use these axes, but year labels will adjust. 900x400 size works for labels
mmdDegDayPlus5Canoms = ggplot(mmd5Cbyyr,aes(x=Year,y=mmdDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(mmd5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text_repel(aes(label=ifelse(mmdDegDayPlus5C_30>74,as.character(Year),'')),hjust=0.8,vjust=1,nudge_y=20,nudge_x=-3,size=3.5,segment.colour=NA)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(b) USC00455704: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
mmdDegDayPlus5Canoms

#112622 - perfect, all plots will use these axes, but year labels will adjust. 900x400 size works for labels
wkdDegDayPlus5Canoms = ggplot(wkd5Cbyyr,aes(x=Year,y=wkdDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(wkd5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text_repel(aes(label=ifelse(wkdDegDayPlus5C_30>100,as.character(Year),'')),hjust=0.8,vjust=0.5,nudge_y=5,nudge_x=-1,size=3.5,segment.colour=NA)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(c) USC00359316: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
wkdDegDayPlus5Canoms

#112622 - perfect, all plots will use these axes, but year labels will adjust. 900x400 size works for labels
miaDegDayPlus5Canoms = ggplot(mia5Cbyyr,aes(x=Year,y=miaDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(mia5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text_repel(aes(label=ifelse(miaDegDayPlus5C_30>99,as.character(Year),'')),hjust=0.8,vjust=0.5,nudge_y=10,nudge_x=-1.5,size=3.5,segment.colour=NA)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(d) USW00024225: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
miaDegDayPlus5Canoms

mp_anom <- ggarrange(f1eDegDayPlus5Canoms, mmdDegDayPlus5Canoms, wkdDegDaysPlus5Canoms, miaDegDayPlus5Canoms,ncol=1, nrow=4)
mp_anom
#don't need  labels=c("a", "b", "c", "d") argument in ggarrange b/c there are labels in the subgraphs already

#103023 - remaking plots at higher resolution, by rerunning code above but with "x" in front of name object
#also adjusting the theme to have "axis.title.x=element_blank(),axis.text.x=element_blank()" in theme()
#also some of the geom_text_repels need adjustment in the nudge values
xf1eDegDayPlus5Canoms = ggplot(f1e5Cbyyr,aes(x=Year,y=f1eDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
     geom_smooth(data=as.data.frame(f1e5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
                 color="black",fill="grey20",alpha=0.2,size=0.5)+
     geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
     geom_text_repel(aes(label=ifelse(f1eDegDayPlus5C_30>50,as.character(Year),'')),hjust=0.8,vjust=1,nudge_y=16,nudge_x=-0.75,size=3.5,segment.colour=NA)+
     labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(a) USC00452914: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
     scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
     scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
     scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
     theme(panel.background=element_blank(),axis.title.x=element_blank(),axis.text.x=element_blank(),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
           legend.spacing.y = unit(5, "mm"), 
           legend.background = element_rect(fill="white"),
           legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
           panel.border = element_rect(colour = "black", fill=NA, size=2))

xmmdDegDayPlus5Canoms <- ggplot(mmd5Cbyyr,aes(x=Year,y=mmdDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
     geom_smooth(data=as.data.frame(mmd5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
                 color="black",fill="grey20",alpha=0.2,size=0.5)+
     geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
     geom_text_repel(aes(label=ifelse(mmdDegDayPlus5C_30>74,as.character(Year),'')),hjust=0.8,vjust=1,nudge_y=16,nudge_x=-0.75,size=3.5,segment.colour=NA)+
     labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(b) USC00455704: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
     scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
     scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
     scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
     theme(panel.background=element_blank(),axis.title.x=element_blank(),axis.text.x=element_blank(),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
           legend.spacing.y = unit(5, "mm"), 
           legend.background = element_rect(fill="white"),
           legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
           panel.border = element_rect(colour = "black", fill=NA, size=2))

xwkdDegDayPlus5Canoms <- ggplot(wkd5Cbyyr,aes(x=Year,y=wkdDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
    geom_smooth(data=as.data.frame(wkd5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
                color="black",fill="grey20",alpha=0.2,size=0.5)+
    geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
    geom_text_repel(aes(label=ifelse(wkdDegDayPlus5C_30>100,as.character(Year),'')),hjust=0.8,vjust=0.5,nudge_y=6,nudge_x=-0.75,size=3.5,segment.colour=NA)+
    labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(c) USC00359316: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
    scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
    scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
    scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
    theme(panel.background=element_blank(),axis.title.x=element_blank(),axis.text.x=element_blank(),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
          legend.spacing.y = unit(5, "mm"), 
          legend.background = element_rect(fill="white"),
          legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
          panel.border = element_rect(colour = "black", fill=NA, size=2))

xmiaDegDayPlus5Canoms <- ggplot(mia5Cbyyr,aes(x=Year,y=miaDegDayPlus5C_30_noNA,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(mia5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text_repel(aes(label=ifelse(miaDegDayPlus5C_30>99,as.character(Year),'')),hjust=0.8,vjust=0.5,nudge_y=10.5,nudge_x=0,size=3.5,segment.colour=NA)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(d) USW00024225: Summed daily anomalies \u2265 5\u00b0C during AMJ periods from 1940-2021")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,210),breaks=c(0,25,50,75,100,125,150,175,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))

mp_anom <- ggarrange(xf1eDegDayPlus5Canoms, xmmdDegDayPlus5Canoms, xwkdDegDayPlus5Canoms, xmiaDegDayPlus5Canoms,ncol=1, nrow=4)
mp_anom
#note the viewer window needs to be relatively big for the ggarrange print to not throw an error
ggsave(filename="Reyes_Sfig5.png",path = "C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\Drafts\\SubmissionCopies\\AcceptInPrinciple_October2023", width=25, height=37, units="cm", device='png', dpi=600)
#updated and higher res version of this plot.

prsDegDayPlus5Canomslm = ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(prs5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
   geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(PRSDegDayPlus5C_30>150,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-5,nudge_x=0,size=3.5)+
   annotate("text",x=2012.85,y=6,label="2011",size=3.5)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(b) Summed daily anomalies \u2265 5\u00b0C during AMJ period annually")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2020))+
   scale_y_continuous(limits=c(0,275),breaks=c(0,50,100,150,200,250,275),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
prsDegDayPlus5Canomslm

f1eDegDayPlus5Canoms = ggplot(f1e5Cbyyr,aes(x=Year,y=f1eDegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(f1e5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(f1eDegDayPlus5C_30>50,as.character(Year),'')),hjust=1,vjust=1,nudge_y=8,nudge_x=0,size=2.4)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(a) Summed daily anomalies \u2265 5\u00b0C during AMJ period annually")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1940,2021),breaks=c(1940,1945,1955,1965,1975,1985,1995,2005,2015,2020))+
   scale_y_continuous(limits=c(0,125),breaks=c(0,25,50,75,100,125),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
f1eDegDayPlus5Canoms



#this is figure 4 on the long-term change at the PDX airport
#03/17/22: I think, after reviewing data from multiple stations, that the DegDayPlus5C is the metric to graph (_30, too). Repeat the above station analysis on the PDX airport station, then plot in ggplot. may want to check if the analysis works out the same way

piaall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PortlandAirportHistoricalDaily3821.csv",header=T)

PIADegDayPlus5C_30 = vector()
PIADayCountPlus5C_30 = vector()

for(i in 1938:2021){
      PIADegDayPlus5C_30[i-1937] <- sum(subset(subset(subset(piaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      PIADayCountPlus5C_30[i-1937] <- nrow(subset(subset(subset(piaall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      }

pia5Cbyyr = data.frame(Year=seq(1938,2021), PIADegDayPlus5C_30, PIADayCountPlus5C_30)
pia5Cbyyr$PIADegExpOver5C_30 <- pia5Cbyyr$PIADegDayPlus5C_30 - (5*PIADayCountPlus5C_30)

ggplot(pia5Cbyyr,aes(x=Year,y=PIADegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(pia5Cbyyr,aes(x=Year,y=PIADegExpOver5C_30,label=Year),na.rm=F) + geom_point()
ggplot(pia5Cbyyr,aes(x=Year,y=PIADayCountPlus5C_30,label=Year),na.rm=F) + geom_point()

SA5Crsq = vector()
SA5Cp = vector()
SA5Crsq.30 = vector()
SA5Cp.30 = vector()
SA5CDDrsq.30 = vector()
SA5CDDp.30 = vector()

for(i in 1938:2021){
      SA5Crsq[i-1937] <- summary(lm(subset(pdx5Cbyyr,Year>=i)[,6]~subset(pdx5Cbyyr,Year>=i)[,1]))$r.squared
      SA5Cp[i-1937] <- summary(lm(subset(pdx5Cbyyr,Year>=i)[,6]~subset(pdx5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5Crsq.30[i-1937] <- summary(lm(subset(pdx5Cbyyr,Year>=i)[,7]~subset(pdx5Cbyyr,Year>=i)[,1]))$r.squared
      SA5Cp.30[i-1937] <- summary(lm(subset(pdx5Cbyyr,Year>=i)[,7]~subset(pdx5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDrsq.30[i-1937] <- summary(lm(subset(pdx5Cbyyr,Year>=i)[,3]~subset(pdx5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30[i-1937] <- summary(lm(subset(pdx5Cbyyr,Year>=i)[,3]~subset(pdx5Cbyyr,Year>=i)[,1]))$coefficients[8]      
      }

plot(seq(1938,2021),SA5CDDrsq.30,xlim=c(1938,2015),ylim=c(0,1))
plot(seq(1938,2021),SA5CDDp.30,xlim=c(1938,2015),ylim=c(0,.10))
plot(seq(1938,2021),SA5Cp.30,xlim=c(1980,2015),ylim=c(0,0.1))

pia5Csince93 <- cbind("Year"=pia5Cbyyr[56:84,1],"DegDayPlus5C_30"=pia5Cbyyr[56:84,2])
summary(lm(data=as.data.frame(pia5Csince93),Year~DegDayPlus5C_30))
pia5Cbyyr$ENSO <- pdxbyyr$ENSO

pia5Cbyyr$ENSO[1:13] <- c(-0.5,-0.5,1,1.5,1,-1,0,0,0,0,0,0,-1)
#pia5Cbyyr now has an ENSO column that is complete back through the entire record to 1938.

write.csv(pia5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\pia5Cbyyr.csv")


# loess text: method=loess,method.args=list(span=1),
#for reference in the year labels in the plot:
#03/20/22 - trying to figure out how to plot a non-linear plot in this using geom_smooth. The issue (I think), is that using such large values of x causes an overflow of the floating point values(ie b/c x = 1950-2000)
summary(lm(data=as.data.frame(pia5Cbyyr),PIADegDayPlus5C_30~exp(Year-1900)))
pia_lm <- lm(data=as.data.frame(pia5Cbyyr),PIADegDayPlus5C_30~exp(Year-1900))
predict(pia_lm)
#these predicted values are garbage. I do not think the nls line is valuable- the non-linear (or lm of the exponent model) predicted values are trash- they are flat then they are steep and they do not appear to fit the points very well (though the model does come back with the parameters being significant). imho it is also more honest to use the linear since it is a linear trend that emerges from the background warming.

pia_nls <- (nls(data=as.data.frame(pia5Cbyyr),PIADegDayPlus5C_30~(a*exp(r*(Year-1900))),start=list(a=0.00000000002,r=0.015)))
predict(pia_nls)

summary(lm(as.data.frame(pia5Csince93)$DegDayPlus5C_30~as.data.frame(pia5Csince93)$Year))

#sensitivity analysis of defining the start point of the linear section
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1938:2021){
      SA5CDDrsq.30x[i-1937] <- summary(lm(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2]))$r.squared
      SA5CDDp.30x[i-1937] <- summary(lm(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2]))$coefficients[8]
      SA5CDDs.30x[i-1937] <- summary(lm(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2]))$coefficients[2]
      }

# in long-term trends in summed daily anomalies \u2265 5\u00b0C during AMJ period annually, 

#plot of R^2's on the models with various starting years
plot(seq(1938,2021),SA5CDDrsq.30x,xlim=c(1938,2021),ylim=c(0,1))
#plot of P-values on the models with various starting years
plot(seq(1938,2021),SA5CDDp.30x,xlim=c(1938,2021),ylim=c(0,1),pch=16)
abline(a=0.05,b=0)
piaSA5CDDp.30x <- data.frame("Year"=seq(1938,2021),"Pval"=SA5CDDp.30x)
ggplot(piaSA5CDDp.30x,aes(x=Year,y=DegDayPlus5C_30,label=Year),na.rm=F) + geom_point() + geom_hline(aes(yintercept=0.05)) + scale_x_continuous(limits=c(1938,2021),breaks=c(1938,1945,1955,1965,1975,1985,1995,2005,2015,2021))+ scale_y_continuous(limits=c(0,0.8),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8))+ labs(x="Starting Year",y="P-value",title="USW00024243: P-values of linear models, by starting year to 2021")+ theme_bw()
#export at 900x300
#plot of slopes for the models with various starting years
plot(seq(1938,2021),SA5CDDs.30x,xlim=c(1938,2021),pch=16)
abline(a=0.05,b=0)

#sensitivity analysis of defining the start point of the linear section (for Marion Forks station)
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1949:2021){
      SA5CDDrsq.30x[i-1948] <- summary(lm(subset(mfh5Cbyyr,Year>=i)[,2]~subset(mfh5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30x[i-1948] <- summary(lm(subset(mfh5Cbyyr,Year>=i)[,2]~subset(mfh5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDs.30x[i-1948] <- summary(lm(subset(mfh5Cbyyr,Year>=i)[,2]~subset(mfh5Cbyyr,Year>=i)[,1]))$coefficients[2]
      }
#plot of R^2's on the models with various starting years
plot(seq(1949,2021),SA5CDDrsq.30x,xlim=c(1949,2021),ylim=c(0,1))
#plot of P-values on the models with various starting years
plot(seq(1949,2021),SA5CDDp.30x,xlim=c(1949,2021),ylim=c(0,1)); abline(a=0.05,b=0)
#plot of slopes for the models with various starting years
plot(seq(1949,2021),SA5CDDs.30x,xlim=c(1949,2021))

#sensitivity analysis graphs
#export at 900x300, adjust height in Word to 2" (when individually, but ggarrange gets around that)
# each is constructed from a data frame following the loop that builds SA5CDDp.30x
#PDX airport
piaSA5CDD.30x <- data.frame("Year"=seq(1938,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Station"=rep("USW00024243; Fig. 4(b)",length(SA5CDDs.30x)))
piapr2 <- ggplot(piaSA5CDD.30x,aes(x=Year,y=Pval,label=Year),na.rm=F) + geom_point() + geom_hline(aes(yintercept=0.05),alpha=0.5)+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(e) USW00024243: P-values of linear models, from starting year to 2021")+ theme_bw()

pias <- ggplot(piaSA5CDD.30x,aes(x=Year,y=Slopes,label=Year),na.rm=F) + geom_line() + geom_hline(aes(yintercept=0),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(-1,9),breaks=c(-1,0,1,2,3,4,5,6,7,8,9))+ labs(x="Starting Year",y="Slope",title="(e) USW00024243: Slope of trendline, from starting year to 2021")+ theme_bw()

ggplot(piaSA5CDD.30x) + geom_point(aes(x=Year,y=DegDayPlus5C_30),color="black",na.rm=F) + geom_point(aes(x=Year,y=R2),color="blue",na.rm=F) + geom_hline(aes(yintercept=0.05))+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(d) USW00024225: P-values of linear models, from starting year to 2021")+ theme_bw()      

#Forks 1 E
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1908:2021){
      SA5CDDrsq.30x[i-1907] <- summary(lm(subset(f1e5Cbyyr,Year>=i)[,2]~subset(f1e5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30x[i-1907] <- summary(lm(subset(f1e5Cbyyr,Year>=i)[,2]~subset(f1e5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDs.30x[i-1907] <- summary(lm(subset(f1e5Cbyyr,Year>=i)[,2]~subset(f1e5Cbyyr,Year>=i)[,1]))$coefficients[2]
      }
f1eSA5CDD.30x <- data.frame("Year"=seq(1908,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Station"=rep("USC00452914; ED Fig. 6(a)",length(SA5CDDs.30x)))
min(SA5CDDs.30x,na.rm=T)
max(SA5CDDs.30x[1:(length(SA5CDDs.30x)-11)],na.rm=T)
f1epr2 <- ggplot(f1eSA5CDD.30x,aes(x=Year,y=Pval,label=Year),na.rm=F) + geom_point() + geom_hline(aes(yintercept=0.05),alpha=0.5)+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(a) USC00452914: P-values of linear models, from starting year to 2021")+ theme_bw() 

f1es <- ggplot(f1eSA5CDD.30x,aes(x=Year,y=Slopes,label=Year),na.rm=F) + geom_line() + geom_hline(aes(yintercept=0),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(-1,9),breaks=c(-1,0,1,2,3,4,5,6,7,8,9))+ labs(x="Starting Year",y="Slope",title="(a) USC00452914: Slope of trendline, from starting year to 2021")+ theme_bw()

ggplot(f1eSA5CDD.30x) + geom_point(aes(x=Year,y=DegDayPlus5C_30),color="black",na.rm=F) + geom_point(aes(x=Year,y=R2),color="blue",na.rm=F) + geom_hline(aes(yintercept=0.05))+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(d) USW00024225: P-values of linear models, from starting year to 2021")+ theme_bw()      

#Mud Mountain Dam
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1939:2021){
      SA5CDDrsq.30x[i-1938] <- summary(lm(subset(mmd5Cbyyr,Year>=i)[,2]~subset(mmd5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30x[i-1938] <- summary(lm(subset(mmd5Cbyyr,Year>=i)[,2]~subset(mmd5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDs.30x[i-1938] <- summary(lm(subset(mmd5Cbyyr,Year>=i)[,2]~subset(mmd5Cbyyr,Year>=i)[,1]))$coefficients[2]
      }
mmdSA5CDD.30x <- data.frame("Year"=seq(1939,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Station"=rep("USC00455704; ED Fig. 6(b)",length(SA5CDDs.30x)))
min(SA5CDDs.30x[1:(length(SA5CDDs.30x)-11)],na.rm=T)
max(SA5CDDs.30x[1:(length(SA5CDDs.30x)-11)],na.rm=T)
mmdpr2 <- ggplot(mmdSA5CDD.30x,aes(x=Year,y=Pval,label=Year),na.rm=F) + geom_point() + geom_hline(aes(yintercept=0.05),alpha=0.5)+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(b) USC00455704: P-values of linear models, from starting year to 2021")+ theme_bw() 

ggplot(mmdSA5CDD.30x,aes(x=Year,y=Slopes,label=Year),na.rm=F) + geom_line() + geom_hline(aes(yintercept=0),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(-1,9),breaks=c(-1,0,1,2,3,4,5,6,7,8,9))+ labs(x="Starting Year",y="Slope",title="(b) USC00455704: Slope of trendline, from starting year to 2021")+ theme_bw()

ggplot(mmdSA5CDD.30x) + geom_point(aes(x=Year,y=DegDayPlus5C_30),color="black",na.rm=F) + geom_point(aes(x=Year,y=R2),color="blue",na.rm=F) + geom_hline(aes(yintercept=0.05))+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(d) USW00024225: P-values of linear models, from starting year to 2021")+ theme_bw()      

#Wikiup Dam
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1942:2021){
      SA5CDDrsq.30x[i-1941] <- summary(lm(subset(wkd5Cbyyr,Year>=i)[,2]~subset(wkd5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30x[i-1941] <- summary(lm(subset(wkd5Cbyyr,Year>=i)[,2]~subset(wkd5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDs.30x[i-1941] <- summary(lm(subset(wkd5Cbyyr,Year>=i)[,2]~subset(wkd5Cbyyr,Year>=i)[,1]))$coefficients[2]
      }
wkdSA5CDD.30x <- data.frame("Year"=seq(1942,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Station"=rep("USC00359316; ED Fig. 6(c)",length(SA5CDDs.30x)))
min(SA5CDDs.30x[1:(length(SA5CDDs.30x)-11)],na.rm=T)
max(SA5CDDs.30x[1:(length(SA5CDDs.30x)-11)],na.rm=T)
wkdpr2 <- ggplot(wkdSA5CDD.30x,aes(x=Year,y=Pval,label=Year),na.rm=F) + geom_point() + geom_hline(aes(yintercept=0.05),alpha=0.5)+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(c) USC00359316: P-values of linear models, from starting year to 2021")+ theme_bw() 

ggplot(wkdSA5CDD.30x,aes(x=Year,y=Slopes,label=Year),na.rm=F) + geom_line() + geom_hline(aes(yintercept=0),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(-1,10),breaks=c(-1,0,1,2,3,4,5,6,7,8,9,10))+ labs(x="Starting Year",y="Slope",title="(c) USC00359316: Slope of trendline, from starting year to 2021")+ theme_bw()

ggplot(wkdSA5CDD.30x) + geom_point(aes(x=Year,y=DegDayPlus5C_30),color="black",na.rm=F) + geom_point(aes(x=Year,y=R2),color="blue",na.rm=F) + geom_hline(aes(yintercept=0.05))+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(c) USW00024225: P-values of linear models, from starting year to 2021")+ theme_bw()      

#Medford Airport
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1911:2021){
      SA5CDDrsq.30x[i-1910] <- summary(lm(subset(mia5Cbyyr,Year>=i)[,2]~subset(mia5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30x[i-1910] <- summary(lm(subset(mia5Cbyyr,Year>=i)[,2]~subset(mia5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDs.30x[i-1910] <- summary(lm(subset(mia5Cbyyr,Year>=i)[,2]~subset(mia5Cbyyr,Year>=i)[,1]))$coefficients[2]
      }
miaSA5CDD.30x <- data.frame("Year"=seq(1911,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Station"=rep("USW00024225; ED Fig. 6(d)",length(SA5CDDs.30x)))
min(SA5CDDs.30x[1:(length(SA5CDDs.30x)-11)],na.rm=T)
max(SA5CDDs.30x[1:(length(SA5CDDs.30x)-11)],na.rm=T)
miapr2 <- ggplot(miaSA5CDD.30x,aes(x=Year,y=Pval,label=Year),na.rm=F) + geom_point() + geom_hline(aes(yintercept=0.05),alpha=0.5)+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(d) USW00024225: P-values of linear models, by starting year to 2021")+ theme_bw()      

ggplot(miaSA5CDD.30x,aes(x=Year,y=Slopes,label=Year),na.rm=F) + geom_line() + geom_hline(aes(yintercept=0),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(-1,10),breaks=c(-1,0,1,2,3,4,5,6,7,8,9,10))+ labs(x="Starting Year",y="Slope",title="(d) USW00024225: Slope of trendline, from starting year to 2021")+ theme_bw()

ggplot(miaSA5CDD.30x) + geom_point(aes(x=Year,y=DegDayPlus5C_30),color="black",na.rm=F) + geom_point(aes(x=Year,y=R2),color="blue",na.rm=F) + geom_hline(aes(yintercept=0.05))+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(d) USW00024225: P-values of linear models, from starting year to 2021")+ theme_bw()      

pvsa <- ggarrange(f1epr2,mmdpr2,wkdpr2,miapr2,piapr2,
        ncol = 1, nrow = 5)
ggarrange()

#060323 - making a plot that combines the slope lines from all stations into a single plot, and then the same for p-values and R2's

library(data.table)
SA5CDD_lmstats <- rbindlist(list(f1eSA5CDD.30x,mmdSA5CDD.30x,wkdSA5CDD.30x,miaSA5CDD.30x,piaSA5CDD.30x),use.names=TRUE,fill=TRUE)
SA5CDD_lmstats <- rbindlist(list(f1eSA5CDD.30x,mmdSA5CDD.30x,wkdSA5CDD.30x,miaSA5CDD.30x,piaSA5CDD.30x,pszSA5CDD.30x),use.names=TRUE,fill=TRUE)
#Persistent Snow Zone (PRISM); Fig. 4(a)


#900x350 seems like a good dimension when exported individually. ggarrange will preclude that tho
SAsl <- ggplot(SA5CDD_lmstats,aes(x=Year,y=Slopes,group=Station,color=Station)) + geom_line() + geom_hline(aes(yintercept=0),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(-1,10),breaks=c(-1,0,1,2,3,4,5,6,7,8,9,10))+ labs(x="Starting Year",y="Slope",title="Slope of trendlines at selected locations, from starting year to 2021")+ scale_color_manual(breaks=c("USC00452914; ED Fig. 6(a)","USC00455704; ED Fig. 6(b)","USC00359316; ED Fig. 6(c)","USW00024225; ED Fig. 6(d)","Persistent Snow Zone (PRISM); Fig. 4(a)","USW00024243; Fig. 4(b)"),values=c("USC00452914; ED Fig. 6(a)"="blue","USC00455704; ED Fig. 6(b)"="purple","USC00359316; ED Fig. 6(c)"="green3","USW00024225; ED Fig. 6(d)"="red","Persistent Snow Zone (PRISM); Fig. 4(a)"="peru","USW00024243; Fig. 4(b)"="black")) + theme(panel.background=element_blank(), legend.position=c(0.2,0.65),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))

SApv <- ggplot(SA5CDD_lmstats,aes(x=Year,y=Pval,group=Station,color=Station)) + geom_line() + geom_hline(aes(yintercept=0.05),alpha=0.5)+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(b) P-values of trendlines at selected locations, from starting year to 2021")+ scale_color_manual(breaks=c("USC00452914; ED Fig. 6(a)","USC00455704; ED Fig. 6(b)","USC00359316; ED Fig. 6(c)","USW00024225; ED Fig. 6(d)","Persistent Snow Zone (PRISM); Fig. 4(a)","USW00024243; Fig. 4(b)"),values=c("USC00452914; ED Fig. 6(a)"="blue","USC00455704; ED Fig. 6(b)"="purple","USC00359316; ED Fig. 6(c)"="green3","USW00024225; ED Fig. 6(d)"="red","Persistent Snow Zone (PRISM); Fig. 4(a)"="peru","USW00024243; Fig. 4(b)"="black")) + theme(panel.background=element_blank(), legend.position=c(0.2,0.65),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))

SAr2 <- ggplot(SA5CDD_lmstats,aes(x=Year,y=R2,group=Station,color=Station)) + geom_line() + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="R-squared",title="(c) R-squared of trendlines at selected locations, from starting year to 2021")+ scale_color_manual(breaks=c("USC00452914; ED Fig. 6(a)","USC00455704; ED Fig. 6(b)","USC00359316; ED Fig. 6(c)","USW00024225; ED Fig. 6(d)","Persistent Snow Zone (PRISM); Fig. 4(a)","USW00024243; Fig. 4(b)"),values=c("USC00452914; ED Fig. 6(a)"="blue","USC00455704; ED Fig. 6(b)"="purple","USC00359316; ED Fig. 6(c)"="green3","USW00024225; ED Fig. 6(d)"="red","Persistent Snow Zone (PRISM); Fig. 4(a)"="peru","USW00024243; Fig. 4(b)"="black")) + theme(panel.background=element_blank(), legend.position=c(0.2,0.65),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))

library(ggpubr)
SAallstats <- ggarrange(SAsl,SApv,SAr2,ncol=1,nrow=3)

#061423 - redoing the sensitivity analysis with robust linear modeling due to mild heteroscedasticity from the extremes in 2016 and to some extent 2021 and 2011.
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDphc3.30x = vector()
SA5CDDs.30x = vector()
for(i in 1981:2021){
      SA5CDDrsq.30x[i-1980] <- summary(lm_robust(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1980] <- summary(lm(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDphc3.30x[i-1980] <- summary(lm_robust(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[8]
      SA5CDDs.30x[i-1980] <- summary(lm_robust(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[2]
      }
pszSA5CDD.30x <- data.frame("Year"=seq(1981,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Pval_HC3"=SA5CDDphc3.30x,"Station"=rep("Persistent Snow Zone (PRISM); Fig. 4(a)",length(SA5CDDs.30x)))

SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDphc3.30x = vector()
SA5CDDs.30x = vector()
for(i in 1938:2021){
      SA5CDDrsq.30x[i-1937] <- summary(lm_robust(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1937] <- summary(lm(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2]))$coefficients[8]
      SA5CDDphc3.30x[i-1937] <- summary(lm_robust(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2],se_type="HC3"))$coefficients[8]
      SA5CDDs.30x[i-1937] <- summary(lm_robust(subset(pia5Cbyyr,Year>=i)[,3]~subset(pia5Cbyyr,Year>=i)[,2],se_type="HC3"))$coefficients[2]
      }
piaSA5CDD.30x <- data.frame("Year"=seq(1938,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Pval_HC3"=SA5CDDphc3.30x,"Station"=rep("USW00024243; Fig. 4(b)",length(SA5CDDs.30x)))

SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDphc3.30x = vector()
SA5CDDs.30x = vector()
for(i in 1908:2021){
      SA5CDDrsq.30x[i-1907] <- summary(lm_robust(subset(f1e5Cbyyr,Year>=i)[,2]~subset(f1e5Cbyyr,Year>=i)[,1],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1907] <- summary(lm(subset(f1e5Cbyyr,Year>=i)[,2]~subset(f1e5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDphc3.30x[i-1907] <- summary(lm_robust(subset(f1e5Cbyyr,Year>=i)[,2]~subset(f1e5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[8]
      SA5CDDs.30x[i-1907] <- summary(lm_robust(subset(f1e5Cbyyr,Year>=i)[,2]~subset(f1e5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[2]
      }
f1eSA5CDD.30x <- data.frame("Year"=seq(1908,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Pval_HC3"=SA5CDDphc3.30x,"Station"=rep("USC00452914; ED Fig. 6(a)",length(SA5CDDs.30x)))

SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDphc3.30x = vector()
SA5CDDs.30x = vector()
for(i in 1939:2021){
      SA5CDDrsq.30x[i-1938] <- summary(lm_robust(subset(mmd5Cbyyr,Year>=i)[,2]~subset(mmd5Cbyyr,Year>=i)[,1],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1938] <- summary(lm(subset(mmd5Cbyyr,Year>=i)[,2]~subset(mmd5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDphc3.30x[i-1938] <- summary(lm_robust(subset(mmd5Cbyyr,Year>=i)[,2]~subset(mmd5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[8]
      SA5CDDs.30x[i-1938] <- summary(lm_robust(subset(mmd5Cbyyr,Year>=i)[,2]~subset(mmd5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[2]
      }
mmdSA5CDD.30x <- data.frame("Year"=seq(1939,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Pval_HC3"=SA5CDDphc3.30x,"Station"=rep("USC00455704; ED Fig. 6(b)",length(SA5CDDs.30x)))

SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDphc3.30x = vector()
SA5CDDs.30x = vector()
for(i in 1942:2021){
      SA5CDDrsq.30x[i-1941] <- summary(lm_robust(subset(wkd5Cbyyr,Year>=i)[,2]~subset(wkd5Cbyyr,Year>=i)[,1],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1941] <- summary(lm(subset(wkd5Cbyyr,Year>=i)[,2]~subset(wkd5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDphc3.30x[i-1941] <- summary(lm_robust(subset(wkd5Cbyyr,Year>=i)[,2]~subset(wkd5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[8]
      SA5CDDs.30x[i-1941] <- summary(lm_robust(subset(wkd5Cbyyr,Year>=i)[,2]~subset(wkd5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[2]
      }
wkdSA5CDD.30x <- data.frame("Year"=seq(1942,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Pval_HC3"=SA5CDDphc3.30x,"Station"=rep("USC00359316; ED Fig. 6(c)",length(SA5CDDs.30x)))

SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDphc3.30x = vector()
SA5CDDs.30x = vector()
for(i in 1911:2021){
      SA5CDDrsq.30x[i-1910] <- summary(lm_robust(subset(mia5Cbyyr,Year>=i)[,2]~subset(mia5Cbyyr,Year>=i)[,1],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1910] <- summary(lm(subset(mia5Cbyyr,Year>=i)[,2]~subset(mia5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDphc3.30x[i-1910] <- summary(lm_robust(subset(mia5Cbyyr,Year>=i)[,2]~subset(mia5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[8]      
      SA5CDDs.30x[i-1910] <- summary(lm_robust(subset(mia5Cbyyr,Year>=i)[,2]~subset(mia5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[2]
      }
miaSA5CDD.30x <- data.frame("Year"=seq(1911,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Pval_HC3"=SA5CDDphc3.30x,"Station"=rep("USW00024225; ED Fig. 6(d)",length(SA5CDDs.30x)))

library(data.table)
SA5CDD_lmstats <- rbindlist(list(f1eSA5CDD.30x,mmdSA5CDD.30x,wkdSA5CDD.30x,miaSA5CDD.30x,piaSA5CDD.30x,pszSA5CDD.30x),use.names=TRUE,fill=TRUE)
write.csv(SA5CDD_lmstats,file="C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\SensitivityAnalysis5CDD_lmstats.csv")

SA5CDD_lmstats <- read.csv(file="C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\SensitivityAnalysis5CDD_lmstats.csv",header=TRUE)
#900x350 seems like a good dimension when exported individually. ggarrange will preclude that tho
SAsl <- ggplot(SA5CDD_lmstats,aes(x=Year,y=Slopes,group=Station,color=Station)) + geom_line() + geom_hline(aes(yintercept=0),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(-1,10),breaks=c(-1,0,1,2,3,4,5,6,7,8,9,10))+ labs(x="Starting Year",y="Slope",title="Slope of trendlines at selected locations, from starting year to 2021")+ scale_color_manual(breaks=c("USC00452914; Supplementary Fig. 5(a)","USC00455704; Supplementary Fig. 5(b)","USC00359316; Supplementary Fig. 5(c)","USW00024225; Supplementary Fig. 5(d)","Persistent Snow Zone (PRISM); Fig. 4(a)","USW00024243; Fig. 4(b)"),values=c("USC00452914; Supplementary Fig. 5(a)"="blue","USC00455704; Supplementary Fig. 5(b)"="purple","USC00359316; Supplementary Fig. 5(c)"="green3","USW00024225; Supplementary Fig. 5(d)"="red","Persistent Snow Zone (PRISM); Fig. 4(a)"="peru","USW00024243; Fig. 4(b)"="black")) + theme(panel.background=element_blank(), legend.position=c(0.2,0.65),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))
SApvhc3 <- ggplot(SA5CDD_lmstats,aes(x=Year,y=Pval_HC3,group=Station,color=Station)) + geom_line() + geom_hline(aes(yintercept=0.05),alpha=0.5)+ geom_hline(aes(yintercept=0.1),alpha=0.5) + scale_x_continuous(limits=c(1940,2010),breaks=c(1940,1950,1960,1970,1980,1990,2000,2010))+ scale_y_continuous(limits=c(0,1),breaks=c(0,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))+ labs(x="Starting Year",y="P-value",title="(b) P-values of trendlines at selected locations, from starting year to 2021")+ scale_color_manual(breaks=c("USC00452914; ED Fig. 6(a)","USC00455704; ED Fig. 6(b)","USC00359316; ED Fig. 6(c)","USW00024225; ED Fig. 6(d)","Persistent Snow Zone (PRISM); Fig. 4(a)","USW00024243; Fig. 4(b)"),values=c("USC00452914; ED Fig. 6(a)"="blue","USC00455704; ED Fig. 6(b)"="purple","USC00359316; ED Fig. 6(c)"="green3","USW00024225; ED Fig. 6(d)"="red","Persistent Snow Zone (PRISM); Fig. 4(a)"="peru","USW00024243; Fig. 4(b)"="black")) + theme(panel.background=element_blank(), legend.position=c(0.2,0.65),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))

#to export:
png("Reyes_EDfig7.png",width=2700,height=1050,res=300)
png("Reyes_Sfig7.png",width=5400,height=2100,res=600)
SAsl
dev.off()

#read in csv of portland airport
pia5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\pia5Cbyyr.csv",header=T)

library(scales)
library(RColorBrewer)
library(colorspace)

#most current graph as of 111722. paradise ranger station was exported as 1100 x 450 pixels. settled on 1100x420 for this one
#small update and re-export on 101123
DegDayPlus5Canoms <- ggplot(pia5Cbyyr,aes(x=Year,y=PIADegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(pia5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(PIADegDayPlus5C_30>60,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-3,nudge_x=0,size=3.5)+
   annotate("text",x=2012.85,y=6,label="2011",size=3.5)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title=bquote(bold("(b)")~ " Summed daily anomalies \u2265 5\u00b0C during AMJ period annually"))+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1938,2021),breaks=c(1938,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,130),breaks=c(0,25,50,75,100,125),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
DegDayPlus5Canoms

#to export to wd:
png("Fig4b.png",width=3200,height=1400,res=300)
png("Fig4b.png",width=6400,height=2800,res=300)
DegDayPlus5Canoms
dev.off()

#earlier polished version of plot from early 2022   
DegDayPlus5Canoms = ggplot(pia5Cbyyr,aes(x=Year,y=PIADegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(pia5Csince93),aes(x=Year,y=DegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(PIADegDayPlus5C_30>60,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-3,nudge_x=0,size=3.5)+
   annotate("text",x=2012.85,y=6,label="2011",size=3.5)+
   labs(x="Year",y="Degree-days above daily normal",title="Cumulative degree-days above normal from all AMJ days with a \u2265 5\u00b0C daily anomaly")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1938,2021),breaks=c(1938,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,130),breaks=c(0,25,50,75,100,125),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
DegDayPlus5Canoms

# graphing code not used
   geom_text(aes(label=ifelse(DegExpOver5C_A>40|Year>2010,as.character(Year),'')),hjust=-0.25,vjust=0.25,size=3.5)+
labels=c("Very Strong\nEl Ni\u00f1o","Strong\nEl Ni\u00f1o","Moderate\nEl Ni\u00f1o","Weak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a","Moderate\nLa Ni\u00f1a","Strong La\nNi\u00f1a"),
,labels=c("Very Strong El Ni\u00f1o","Strong El Ni\u00f1o","Moderate El Ni\u00f1o","Weak El Ni\u00f1o","Neutral","Weak La Ni\u00f1a","Moderate La Ni\u00f1a","Strong La Ni\u00f1a")
 scale_fill_discrete_diverging(name="ENSO class",palette="Blue-Red 3",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5,-2),limits=factor(c(2,1.5,1,0.5,0,-0.5,-1,-1.5,-2)),labels=c("Very Strong El Ni\u00f1o","Strong El Ni\u00f1o","Moderate El Ni\u00f1o","Weak El Ni\u00f1o","Neutral","Weak La Ni\u00f1a","Moderate La Ni\u00f1a","Strong La Ni\u00f1a","\n"),na.value="grey50",drop=FALSE,oob=rescale_none)+
     
     scale_fill_gradientn(name="ENSO class",palette="RdBu",direction=-1,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),na.value="black",drop=FALSE)+
     breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),


###in RStudio on 040422 - tried to get the tools working to do a bunch of post-processing outside of ArcMap
#first job was to convert .bil to netcdf (.nc)
#I did this in RStudio, including installing something called Rtools from a .exe This seems to be required to install packages in Rstudio. I had tried to just use it in the R GUI console but it kept throwing an error around Rcpp and terra that I couldn't figure out. So, I tried it in Rstudio and it seems good.

library("raster")
library("ncdf4")

#test in a specific year
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_compressed\\PRISM_test_1981\\PRISM_tmean_stable_4kmD2_19810101_19811231_bil")
f<-list.files(pattern = "\\.bil$")
for (i in 1:length(f)){
    rd<-raster(f[i]) # read your bil files
    name_nc<-tools::file_path_sans_ext(f[i])
    rnc <- writeRaster(rd, filename=paste(name_nc,".nc",sep=""), format="CDF", overwrite=TRUE)
    }
    
#this writes a .nc netcdf file to the directory I'm working in. Very cool and I think I can do it with all the years in a matter of minutes.

#to do next: clip files, average days over the 30-year period, reproject, resample, extract by mask, zonal statistics.

##041522 more work in RStudio. checking out using the prism package and its tools for organizing and navigating the prism rasters
library(prism)

#made a folder to play around in
prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R")

#dl min temp for the heat dome days
get_prism_dailys(type = "tmin", minDate = "2021-06-25", maxDate = "2021-06-30", keepZip = FALSE)

#trying a loop 041622
# loop doesn't work, will have to just do 31 lines for the ranges I want each year
#in future runs you should cut down the days selected. 062921 is the warmest, but you could do like 0625 - 0701 and still get a good picture. 
prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax")
get_prism_dailys(type = "tmax", minDate = "1991-06-20", maxDate = "1991-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1992-06-20", maxDate = "1992-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1993-06-20", maxDate = "1993-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1994-06-20", maxDate = "1994-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1995-06-20", maxDate = "1995-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1996-06-20", maxDate = "1996-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1997-06-20", maxDate = "1997-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1998-06-20", maxDate = "1998-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "1999-06-20", maxDate = "1999-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2000-06-20", maxDate = "2000-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2001-06-20", maxDate = "2001-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2002-06-20", maxDate = "2002-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2003-06-20", maxDate = "2003-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2004-06-20", maxDate = "2004-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2005-06-20", maxDate = "2005-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2006-06-20", maxDate = "2006-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2007-06-20", maxDate = "2007-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2008-06-20", maxDate = "2008-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2009-06-20", maxDate = "2009-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2010-06-20", maxDate = "2010-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2011-06-20", maxDate = "2011-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2012-06-20", maxDate = "2012-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2013-06-20", maxDate = "2013-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2014-06-20", maxDate = "2014-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2015-06-20", maxDate = "2015-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2016-06-20", maxDate = "2016-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2017-06-20", maxDate = "2017-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2018-06-20", maxDate = "2018-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2019-06-20", maxDate = "2019-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2020-06-20", maxDate = "2020-07-05", keepZip = FALSE)
get_prism_dailys(type = "tmax", minDate = "2021-06-20", maxDate = "2021-07-05", keepZip = FALSE)

#create spatial extent raster to use for cropping
wpnw <- as(extent(-125.0208, -118, 41.5 ,49.9375), 'SpatialPolygons')
#assign cropping extent to same coordinate system as one of the rasters (062921 tmax in this case)
crs(wpnw) <- crs(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210629_bil\\PRISM_tmax_stable_4kmD2_20210629_bil.bil"))
#check results
extent(wpnw)
#looks great

#crop a raster
wpnw_tmax_062921 <- crop(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210629_bil\\PRISM_tmax_stable_4kmD2_20210629_bil.bil"),wpnw)
#check by plotting cropped
plot(wpnw_tmax_062921)
#this works swimmingly. Time to make a loop that crops all the tmaxes

#said loop
wpnw_list = c()
UStmax<-pd_to_file(prism_archive_ls())
for (i in 1:length(UStmax)){
    wpnw_list <- append(wpnw_list, assign(paste0("wpnw_tmax_",substr(UStmax[i],132,139)),crop(raster(UStmax[i]),wpnw)))
    }

#I'm finding the list weird to work with. Switching to just making the raster objects I need
for (i in 1:length(UStmax)){
    assign(paste0("wpnw_tmax_",substr(UStmax[i],132,139)),crop(raster(UStmax[i]),wpnw))
    }

#manually calculating daily 30yr norms from 1991-2020
tmax_30yr_0620 <- mean(wpnw_tmax_19910620,wpnw_tmax_19920620,wpnw_tmax_19930620,wpnw_tmax_19940620,
               wpnw_tmax_19950620,wpnw_tmax_19960620,wpnw_tmax_19970620,wpnw_tmax_19980620,
               wpnw_tmax_19990620,wpnw_tmax_20000620,wpnw_tmax_20010620,wpnw_tmax_20020620,
               wpnw_tmax_20030620,wpnw_tmax_20040620,wpnw_tmax_20050620,wpnw_tmax_20060620,
               wpnw_tmax_20070620,wpnw_tmax_20080620,wpnw_tmax_20090620,wpnw_tmax_20100620,
               wpnw_tmax_20110620,wpnw_tmax_20120620,wpnw_tmax_20130620,wpnw_tmax_20140620,
               wpnw_tmax_20150620,wpnw_tmax_20160620,wpnw_tmax_20170620,wpnw_tmax_20180620,
               wpnw_tmax_20190620,wpnw_tmax_20200620)

tmax_30yr_0621 <- mean(wpnw_tmax_19910621,wpnw_tmax_19920621,wpnw_tmax_19930621,wpnw_tmax_19940621,
               wpnw_tmax_19950621,wpnw_tmax_19960621,wpnw_tmax_19970621,wpnw_tmax_19980621,
               wpnw_tmax_19990621,wpnw_tmax_20000621,wpnw_tmax_20010621,wpnw_tmax_20020621,
               wpnw_tmax_20030621,wpnw_tmax_20040621,wpnw_tmax_20050621,wpnw_tmax_20060621,
               wpnw_tmax_20070621,wpnw_tmax_20080621,wpnw_tmax_20090621,wpnw_tmax_20100621,
               wpnw_tmax_20110621,wpnw_tmax_20120621,wpnw_tmax_20130621,wpnw_tmax_20140621,
               wpnw_tmax_20150621,wpnw_tmax_20160621,wpnw_tmax_20170621,wpnw_tmax_20180621,
               wpnw_tmax_20190621,wpnw_tmax_20200621)

tmax_30yr_0622 <- mean(wpnw_tmax_19910622,wpnw_tmax_19920622,wpnw_tmax_19930622,wpnw_tmax_19940622,
               wpnw_tmax_19950622,wpnw_tmax_19960622,wpnw_tmax_19970622,wpnw_tmax_19980622,
               wpnw_tmax_19990622,wpnw_tmax_20000622,wpnw_tmax_20010622,wpnw_tmax_20020622,
               wpnw_tmax_20030622,wpnw_tmax_20040622,wpnw_tmax_20050622,wpnw_tmax_20060622,
               wpnw_tmax_20070622,wpnw_tmax_20080622,wpnw_tmax_20090622,wpnw_tmax_20100622,
               wpnw_tmax_20110622,wpnw_tmax_20120622,wpnw_tmax_20130622,wpnw_tmax_20140622,
               wpnw_tmax_20150622,wpnw_tmax_20160622,wpnw_tmax_20170622,wpnw_tmax_20180622,
               wpnw_tmax_20190622,wpnw_tmax_20200622)

tmax_30yr_0623 <- mean(wpnw_tmax_19910623,wpnw_tmax_19920623,wpnw_tmax_19930623,wpnw_tmax_19940623,
               wpnw_tmax_19950623,wpnw_tmax_19960623,wpnw_tmax_19970623,wpnw_tmax_19980623,
               wpnw_tmax_19990623,wpnw_tmax_20000623,wpnw_tmax_20010623,wpnw_tmax_20020623,
               wpnw_tmax_20030623,wpnw_tmax_20040623,wpnw_tmax_20050623,wpnw_tmax_20060623,
               wpnw_tmax_20070623,wpnw_tmax_20080623,wpnw_tmax_20090623,wpnw_tmax_20100623,
               wpnw_tmax_20110623,wpnw_tmax_20120623,wpnw_tmax_20130623,wpnw_tmax_20140623,
               wpnw_tmax_20150623,wpnw_tmax_20160623,wpnw_tmax_20170623,wpnw_tmax_20180623,
               wpnw_tmax_20190623,wpnw_tmax_20200623)    

tmax_30yr_0624 <- mean(wpnw_tmax_19910624,wpnw_tmax_19920624,wpnw_tmax_19930624,wpnw_tmax_19940624,
               wpnw_tmax_19950624,wpnw_tmax_19960624,wpnw_tmax_19970624,wpnw_tmax_19980624,
               wpnw_tmax_19990624,wpnw_tmax_20000624,wpnw_tmax_20010624,wpnw_tmax_20020624,
               wpnw_tmax_20030624,wpnw_tmax_20040624,wpnw_tmax_20050624,wpnw_tmax_20060624,
               wpnw_tmax_20070624,wpnw_tmax_20080624,wpnw_tmax_20090624,wpnw_tmax_20100624,
               wpnw_tmax_20110624,wpnw_tmax_20120624,wpnw_tmax_20130624,wpnw_tmax_20140624,
               wpnw_tmax_20150624,wpnw_tmax_20160624,wpnw_tmax_20170624,wpnw_tmax_20180624,
               wpnw_tmax_20190624,wpnw_tmax_20200624)

tmax_30yr_0625 <- mean(wpnw_tmax_19910625,wpnw_tmax_19920625,wpnw_tmax_19930625,wpnw_tmax_19940625,
               wpnw_tmax_19950625,wpnw_tmax_19960625,wpnw_tmax_19970625,wpnw_tmax_19980625,
               wpnw_tmax_19990625,wpnw_tmax_20000625,wpnw_tmax_20010625,wpnw_tmax_20020625,
               wpnw_tmax_20030625,wpnw_tmax_20040625,wpnw_tmax_20050625,wpnw_tmax_20060625,
               wpnw_tmax_20070625,wpnw_tmax_20080625,wpnw_tmax_20090625,wpnw_tmax_20100625,
               wpnw_tmax_20110625,wpnw_tmax_20120625,wpnw_tmax_20130625,wpnw_tmax_20140625,
               wpnw_tmax_20150625,wpnw_tmax_20160625,wpnw_tmax_20170625,wpnw_tmax_20180625,
               wpnw_tmax_20190625,wpnw_tmax_20200625)

tmax_30yr_0626 <- mean(wpnw_tmax_19910626,wpnw_tmax_19920626,wpnw_tmax_19930626,wpnw_tmax_19940626,
               wpnw_tmax_19950626,wpnw_tmax_19960626,wpnw_tmax_19970626,wpnw_tmax_19980626,
               wpnw_tmax_19990626,wpnw_tmax_20000626,wpnw_tmax_20010626,wpnw_tmax_20020626,
               wpnw_tmax_20030626,wpnw_tmax_20040626,wpnw_tmax_20050626,wpnw_tmax_20060626,
               wpnw_tmax_20070626,wpnw_tmax_20080626,wpnw_tmax_20090626,wpnw_tmax_20100626,
               wpnw_tmax_20110626,wpnw_tmax_20120626,wpnw_tmax_20130626,wpnw_tmax_20140626,
               wpnw_tmax_20150626,wpnw_tmax_20160626,wpnw_tmax_20170626,wpnw_tmax_20180626,
               wpnw_tmax_20190626,wpnw_tmax_20200626)

tmax_30yr_0627 <- mean(wpnw_tmax_19910627,wpnw_tmax_19920627,wpnw_tmax_19930627,wpnw_tmax_19940627,
               wpnw_tmax_19950627,wpnw_tmax_19960627,wpnw_tmax_19970627,wpnw_tmax_19980627,
               wpnw_tmax_19990627,wpnw_tmax_20000627,wpnw_tmax_20010627,wpnw_tmax_20020627,
               wpnw_tmax_20030627,wpnw_tmax_20040627,wpnw_tmax_20050627,wpnw_tmax_20060627,
               wpnw_tmax_20070627,wpnw_tmax_20080627,wpnw_tmax_20090627,wpnw_tmax_20100627,
               wpnw_tmax_20110627,wpnw_tmax_20120627,wpnw_tmax_20130627,wpnw_tmax_20140627,
               wpnw_tmax_20150627,wpnw_tmax_20160627,wpnw_tmax_20170627,wpnw_tmax_20180627,
               wpnw_tmax_20190627,wpnw_tmax_20200627)

tmax_30yr_0628 <- mean(wpnw_tmax_19910628,wpnw_tmax_19920628,wpnw_tmax_19930628,wpnw_tmax_19940628,
               wpnw_tmax_19950628,wpnw_tmax_19960628,wpnw_tmax_19970628,wpnw_tmax_19980628,
               wpnw_tmax_19990628,wpnw_tmax_20000628,wpnw_tmax_20010628,wpnw_tmax_20020628,
               wpnw_tmax_20030628,wpnw_tmax_20040628,wpnw_tmax_20050628,wpnw_tmax_20060628,
               wpnw_tmax_20070628,wpnw_tmax_20080628,wpnw_tmax_20090628,wpnw_tmax_20100628,
               wpnw_tmax_20110628,wpnw_tmax_20120628,wpnw_tmax_20130628,wpnw_tmax_20140628,
               wpnw_tmax_20150628,wpnw_tmax_20160628,wpnw_tmax_20170628,wpnw_tmax_20180628,
               wpnw_tmax_20190628,wpnw_tmax_20200628)

tmax_30yr_0629 <- mean(wpnw_tmax_19910629,wpnw_tmax_19920629,wpnw_tmax_19930629,wpnw_tmax_19940629,
               wpnw_tmax_19950629,wpnw_tmax_19960629,wpnw_tmax_19970629,wpnw_tmax_19980629,
               wpnw_tmax_19990629,wpnw_tmax_20000629,wpnw_tmax_20010629,wpnw_tmax_20020629,
               wpnw_tmax_20030629,wpnw_tmax_20040629,wpnw_tmax_20050629,wpnw_tmax_20060629,
               wpnw_tmax_20070629,wpnw_tmax_20080629,wpnw_tmax_20090629,wpnw_tmax_20100629,
               wpnw_tmax_20110629,wpnw_tmax_20120629,wpnw_tmax_20130629,wpnw_tmax_20140629,
               wpnw_tmax_20150629,wpnw_tmax_20160629,wpnw_tmax_20170629,wpnw_tmax_20180629,
               wpnw_tmax_20190629,wpnw_tmax_20200629)

tmax_30yr_0630 <- mean(wpnw_tmax_19910630,wpnw_tmax_19920630,wpnw_tmax_19930630,wpnw_tmax_19940630,
               wpnw_tmax_19950630,wpnw_tmax_19960630,wpnw_tmax_19970630,wpnw_tmax_19980630,
               wpnw_tmax_19990630,wpnw_tmax_20000630,wpnw_tmax_20010630,wpnw_tmax_20020630,
               wpnw_tmax_20030630,wpnw_tmax_20040630,wpnw_tmax_20050630,wpnw_tmax_20060630,
               wpnw_tmax_20070630,wpnw_tmax_20080630,wpnw_tmax_20090630,wpnw_tmax_20100630,
               wpnw_tmax_20110630,wpnw_tmax_20120630,wpnw_tmax_20130630,wpnw_tmax_20140630,
               wpnw_tmax_20150630,wpnw_tmax_20160630,wpnw_tmax_20170630,wpnw_tmax_20180630,
               wpnw_tmax_20190630,wpnw_tmax_20200630)

tmax_30yr_0701 <- mean(wpnw_tmax_19910701,wpnw_tmax_19920701,wpnw_tmax_19930701,wpnw_tmax_19940701,
               wpnw_tmax_19950701,wpnw_tmax_19960701,wpnw_tmax_19970701,wpnw_tmax_19980701,
               wpnw_tmax_19990701,wpnw_tmax_20000701,wpnw_tmax_20010701,wpnw_tmax_20020701,
               wpnw_tmax_20030701,wpnw_tmax_20040701,wpnw_tmax_20050701,wpnw_tmax_20060701,
               wpnw_tmax_20070701,wpnw_tmax_20080701,wpnw_tmax_20090701,wpnw_tmax_20100701,
               wpnw_tmax_20110701,wpnw_tmax_20120701,wpnw_tmax_20130701,wpnw_tmax_20140701,
               wpnw_tmax_20150701,wpnw_tmax_20160701,wpnw_tmax_20170701,wpnw_tmax_20180701,
               wpnw_tmax_20190701,wpnw_tmax_20200701)

tmax_30yr_0702 <- mean(wpnw_tmax_19910702,wpnw_tmax_19920702,wpnw_tmax_19930702,wpnw_tmax_19940702,
               wpnw_tmax_19950702,wpnw_tmax_19960702,wpnw_tmax_19970702,wpnw_tmax_19980702,
               wpnw_tmax_19990702,wpnw_tmax_20000702,wpnw_tmax_20010702,wpnw_tmax_20020702,
               wpnw_tmax_20030702,wpnw_tmax_20040702,wpnw_tmax_20050702,wpnw_tmax_20060702,
               wpnw_tmax_20070702,wpnw_tmax_20080702,wpnw_tmax_20090702,wpnw_tmax_20100702,
               wpnw_tmax_20110702,wpnw_tmax_20120702,wpnw_tmax_20130702,wpnw_tmax_20140702,
               wpnw_tmax_20150702,wpnw_tmax_20160702,wpnw_tmax_20170702,wpnw_tmax_20180702,
               wpnw_tmax_20190702,wpnw_tmax_20200702)

tmax_30yr_0703 <- mean(wpnw_tmax_19910703,wpnw_tmax_19920703,wpnw_tmax_19930703,wpnw_tmax_19940703,
               wpnw_tmax_19950703,wpnw_tmax_19960703,wpnw_tmax_19970703,wpnw_tmax_19980703,
               wpnw_tmax_19990703,wpnw_tmax_20000703,wpnw_tmax_20010703,wpnw_tmax_20020703,
               wpnw_tmax_20030703,wpnw_tmax_20040703,wpnw_tmax_20050703,wpnw_tmax_20060703,
               wpnw_tmax_20070703,wpnw_tmax_20080703,wpnw_tmax_20090703,wpnw_tmax_20100703,
               wpnw_tmax_20110703,wpnw_tmax_20120703,wpnw_tmax_20130703,wpnw_tmax_20140703,
               wpnw_tmax_20150703,wpnw_tmax_20160703,wpnw_tmax_20170703,wpnw_tmax_20180703,
               wpnw_tmax_20190703,wpnw_tmax_20200703)

tmax_30yr_0704 <- mean(wpnw_tmax_19910704,wpnw_tmax_19920704,wpnw_tmax_19930704,wpnw_tmax_19940704,
               wpnw_tmax_19950704,wpnw_tmax_19960704,wpnw_tmax_19970704,wpnw_tmax_19980704,
               wpnw_tmax_19990704,wpnw_tmax_20000704,wpnw_tmax_20010704,wpnw_tmax_20020704,
               wpnw_tmax_20030704,wpnw_tmax_20040704,wpnw_tmax_20050704,wpnw_tmax_20060704,
               wpnw_tmax_20070704,wpnw_tmax_20080704,wpnw_tmax_20090704,wpnw_tmax_20100704,
               wpnw_tmax_20110704,wpnw_tmax_20120704,wpnw_tmax_20130704,wpnw_tmax_20140704,
               wpnw_tmax_20150704,wpnw_tmax_20160704,wpnw_tmax_20170704,wpnw_tmax_20180704,
               wpnw_tmax_20190704,wpnw_tmax_20200704)

tmax_30yr_0705 <- mean(wpnw_tmax_19910705,wpnw_tmax_19920705,wpnw_tmax_19930705,wpnw_tmax_19940705,
               wpnw_tmax_19950705,wpnw_tmax_19960705,wpnw_tmax_19970705,wpnw_tmax_19980705,
               wpnw_tmax_19990705,wpnw_tmax_20000705,wpnw_tmax_20010705,wpnw_tmax_20020705,
               wpnw_tmax_20030705,wpnw_tmax_20040705,wpnw_tmax_20050705,wpnw_tmax_20060705,
               wpnw_tmax_20070705,wpnw_tmax_20080705,wpnw_tmax_20090705,wpnw_tmax_20100705,
               wpnw_tmax_20110705,wpnw_tmax_20120705,wpnw_tmax_20130705,wpnw_tmax_20140705,
               wpnw_tmax_20150705,wpnw_tmax_20160705,wpnw_tmax_20170705,wpnw_tmax_20180705,
               wpnw_tmax_20190705,wpnw_tmax_20200705)

#manually substract the norms from the 2021 dailies to make anomaly maps for 2021
#define function, per prism package documentation, to do raster subtraction
anomCalc <- function(x, y) {
  return(x - y)
}

tmax_anom_20210620 <- raster::overlay(wpnw_tmax_20210620,tmax_30yr_0620,fun = anomCalc)
tmax_anom_20210621 <- raster::overlay(wpnw_tmax_20210622,tmax_30yr_0621,fun = anomCalc)
tmax_anom_20210622 <- raster::overlay(wpnw_tmax_20210622,tmax_30yr_0622,fun = anomCalc)
tmax_anom_20210623 <- raster::overlay(wpnw_tmax_20210623,tmax_30yr_0623,fun = anomCalc)
tmax_anom_20210624 <- raster::overlay(wpnw_tmax_20210624,tmax_30yr_0624,fun = anomCalc)
tmax_anom_20210625 <- raster::overlay(wpnw_tmax_20210625,tmax_30yr_0625,fun = anomCalc)
tmax_anom_20210626 <- raster::overlay(wpnw_tmax_20210626,tmax_30yr_0626,fun = anomCalc)
tmax_anom_20210627 <- raster::overlay(wpnw_tmax_20210627,tmax_30yr_0627,fun = anomCalc)
tmax_anom_20210628 <- raster::overlay(wpnw_tmax_20210628,tmax_30yr_0628,fun = anomCalc)
tmax_anom_20210629 <- raster::overlay(wpnw_tmax_20210629,tmax_30yr_0629,fun = anomCalc)
tmax_anom_20210630 <- raster::overlay(wpnw_tmax_20210630,tmax_30yr_0630,fun = anomCalc)
tmax_anom_20210701 <- raster::overlay(wpnw_tmax_20210701,tmax_30yr_0701,fun = anomCalc)
tmax_anom_20210702 <- raster::overlay(wpnw_tmax_20210702,tmax_30yr_0702,fun = anomCalc)
tmax_anom_20210703 <- raster::overlay(wpnw_tmax_20210703,tmax_30yr_0703,fun = anomCalc)
tmax_anom_20210704 <- raster::overlay(wpnw_tmax_20210704,tmax_30yr_0704,fun = anomCalc)
tmax_anom_20210705 <- raster::overlay(wpnw_tmax_20210705,tmax_30yr_0705,fun = anomCalc)

zlim <- c(-8,28)
# set same raster limits and compared adjacent days. 062921 is definitely the warmest anomaly
plot(tmax_anom_20210629,zlim=zlim)

#write the rasters I want to work with later
writeRaster(tmax_anom_20210628, filename="tmax_anom_20210628.bil", format="EHdr", overwrite=FALSE)
writeRaster(tmax_anom_20210629, filename="tmax_anom_20210629.bil", format="EHdr", overwrite=FALSE)
writeRaster(tmax_anom_20210630, filename="tmax_anom_20210630.bil", format="EHdr", overwrite=FALSE)

#let's repeat with the tmin values
#remove some data that I don't need anymore
ls()
rm(list=ls()[405:903])
#repeated some extra to remove a few others

prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin")
get_prism_dailys(type = "tmin", minDate = "1991-06-24", maxDate = "1991-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1992-06-24", maxDate = "1992-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1993-06-24", maxDate = "1993-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1994-06-24", maxDate = "1994-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1995-06-24", maxDate = "1995-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1996-06-24", maxDate = "1996-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1997-06-24", maxDate = "1997-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1998-06-24", maxDate = "1998-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "1999-06-24", maxDate = "1999-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2000-06-24", maxDate = "2000-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2001-06-24", maxDate = "2001-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2002-06-24", maxDate = "2002-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2003-06-24", maxDate = "2003-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2004-06-24", maxDate = "2004-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2005-06-24", maxDate = "2005-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2006-06-24", maxDate = "2006-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2007-06-24", maxDate = "2007-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2008-06-24", maxDate = "2008-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2009-06-24", maxDate = "2009-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2010-06-24", maxDate = "2010-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2011-06-24", maxDate = "2011-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2012-06-24", maxDate = "2012-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2013-06-24", maxDate = "2013-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2014-06-24", maxDate = "2014-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2015-06-24", maxDate = "2015-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2016-06-24", maxDate = "2016-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2017-06-24", maxDate = "2017-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2018-06-24", maxDate = "2018-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2019-06-24", maxDate = "2019-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2020-06-24", maxDate = "2020-07-03", keepZip = FALSE)
get_prism_dailys(type = "tmin", minDate = "2021-06-24", maxDate = "2021-07-03", keepZip = FALSE)

#create spatial extent raster to use for cropping
wpnw <- as(extent(-125.0208, -118, 41.5 ,49.9375), 'SpatialPolygons')
#assign cropping extent to same coordinate system as one of the rasters (062921 tmax in this case)
crs(wpnw) <- crs(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210629_bil\\PRISM_tmin_stable_4kmD2_20210629_bil.bil"))
#check results
extent(wpnw)
#looks great

# disregard this loop, the list is cumbersome
wpnw_list = c()
UStmin<-pd_to_file(prism_archive_ls())

#for (i in 1:length(UStmax)){
#    wpnw_list <- append(wpnw_list, assign(paste0("wpnw_tmax_",substr(UStmax[i],132,139)),crop(raster(UStmax[i]),wpnw)))
#    }

#I'm finding the list weird to work with. Switching to just making the raster objects I need
for (i in 1:length(UStmin)){
    assign(paste0("wpnw_tmin_",substr(UStmin[i],132,139)),crop(raster(UStmin[i]),wpnw))
    }

#manually calculating daily 30yr norms from 1991-2020
tmin_30yr_0624 <- mean(wpnw_tmin_19910624,wpnw_tmin_19920624,wpnw_tmin_19930624,wpnw_tmin_19940624,
               wpnw_tmin_19950624,wpnw_tmin_19960624,wpnw_tmin_19970624,wpnw_tmin_19980624,
               wpnw_tmin_19990624,wpnw_tmin_20000624,wpnw_tmin_20010624,wpnw_tmin_20020624,
               wpnw_tmin_20030624,wpnw_tmin_20040624,wpnw_tmin_20050624,wpnw_tmin_20060624,
               wpnw_tmin_20070624,wpnw_tmin_20080624,wpnw_tmin_20090624,wpnw_tmin_20100624,
               wpnw_tmin_20110624,wpnw_tmin_20120624,wpnw_tmin_20130624,wpnw_tmin_20140624,
               wpnw_tmin_20150624,wpnw_tmin_20160624,wpnw_tmin_20170624,wpnw_tmin_20180624,
               wpnw_tmin_20190624,wpnw_tmin_20200624)

tmin_30yr_0625 <- mean(wpnw_tmin_19910625,wpnw_tmin_19920625,wpnw_tmin_19930625,wpnw_tmin_19940625,
               wpnw_tmin_19950625,wpnw_tmin_19960625,wpnw_tmin_19970625,wpnw_tmin_19980625,
               wpnw_tmin_19990625,wpnw_tmin_20000625,wpnw_tmin_20010625,wpnw_tmin_20020625,
               wpnw_tmin_20030625,wpnw_tmin_20040625,wpnw_tmin_20050625,wpnw_tmin_20060625,
               wpnw_tmin_20070625,wpnw_tmin_20080625,wpnw_tmin_20090625,wpnw_tmin_20100625,
               wpnw_tmin_20110625,wpnw_tmin_20120625,wpnw_tmin_20130625,wpnw_tmin_20140625,
               wpnw_tmin_20150625,wpnw_tmin_20160625,wpnw_tmin_20170625,wpnw_tmin_20180625,
               wpnw_tmin_20190625,wpnw_tmin_20200625)

tmin_30yr_0626 <- mean(wpnw_tmin_19910626,wpnw_tmin_19920626,wpnw_tmin_19930626,wpnw_tmin_19940626,
               wpnw_tmin_19950626,wpnw_tmin_19960626,wpnw_tmin_19970626,wpnw_tmin_19980626,
               wpnw_tmin_19990626,wpnw_tmin_20000626,wpnw_tmin_20010626,wpnw_tmin_20020626,
               wpnw_tmin_20030626,wpnw_tmin_20040626,wpnw_tmin_20050626,wpnw_tmin_20060626,
               wpnw_tmin_20070626,wpnw_tmin_20080626,wpnw_tmin_20090626,wpnw_tmin_20100626,
               wpnw_tmin_20110626,wpnw_tmin_20120626,wpnw_tmin_20130626,wpnw_tmin_20140626,
               wpnw_tmin_20150626,wpnw_tmin_20160626,wpnw_tmin_20170626,wpnw_tmin_20180626,
               wpnw_tmin_20190626,wpnw_tmin_20200626)

tmin_30yr_0627 <- mean(wpnw_tmin_19910627,wpnw_tmin_19920627,wpnw_tmin_19930627,wpnw_tmin_19940627,
               wpnw_tmin_19950627,wpnw_tmin_19960627,wpnw_tmin_19970627,wpnw_tmin_19980627,
               wpnw_tmin_19990627,wpnw_tmin_20000627,wpnw_tmin_20010627,wpnw_tmin_20020627,
               wpnw_tmin_20030627,wpnw_tmin_20040627,wpnw_tmin_20050627,wpnw_tmin_20060627,
               wpnw_tmin_20070627,wpnw_tmin_20080627,wpnw_tmin_20090627,wpnw_tmin_20100627,
               wpnw_tmin_20110627,wpnw_tmin_20120627,wpnw_tmin_20130627,wpnw_tmin_20140627,
               wpnw_tmin_20150627,wpnw_tmin_20160627,wpnw_tmin_20170627,wpnw_tmin_20180627,
               wpnw_tmin_20190627,wpnw_tmin_20200627)

tmin_30yr_0628 <- mean(wpnw_tmin_19910628,wpnw_tmin_19920628,wpnw_tmin_19930628,wpnw_tmin_19940628,
               wpnw_tmin_19950628,wpnw_tmin_19960628,wpnw_tmin_19970628,wpnw_tmin_19980628,
               wpnw_tmin_19990628,wpnw_tmin_20000628,wpnw_tmin_20010628,wpnw_tmin_20020628,
               wpnw_tmin_20030628,wpnw_tmin_20040628,wpnw_tmin_20050628,wpnw_tmin_20060628,
               wpnw_tmin_20070628,wpnw_tmin_20080628,wpnw_tmin_20090628,wpnw_tmin_20100628,
               wpnw_tmin_20110628,wpnw_tmin_20120628,wpnw_tmin_20130628,wpnw_tmin_20140628,
               wpnw_tmin_20150628,wpnw_tmin_20160628,wpnw_tmin_20170628,wpnw_tmin_20180628,
               wpnw_tmin_20190628,wpnw_tmin_20200628)

tmin_30yr_0629 <- mean(wpnw_tmin_19910629,wpnw_tmin_19920629,wpnw_tmin_19930629,wpnw_tmin_19940629,
               wpnw_tmin_19950629,wpnw_tmin_19960629,wpnw_tmin_19970629,wpnw_tmin_19980629,
               wpnw_tmin_19990629,wpnw_tmin_20000629,wpnw_tmin_20010629,wpnw_tmin_20020629,
               wpnw_tmin_20030629,wpnw_tmin_20040629,wpnw_tmin_20050629,wpnw_tmin_20060629,
               wpnw_tmin_20070629,wpnw_tmin_20080629,wpnw_tmin_20090629,wpnw_tmin_20100629,
               wpnw_tmin_20110629,wpnw_tmin_20120629,wpnw_tmin_20130629,wpnw_tmin_20140629,
               wpnw_tmin_20150629,wpnw_tmin_20160629,wpnw_tmin_20170629,wpnw_tmin_20180629,
               wpnw_tmin_20190629,wpnw_tmin_20200629)

tmin_30yr_0630 <- mean(wpnw_tmin_19910630,wpnw_tmin_19920630,wpnw_tmin_19930630,wpnw_tmin_19940630,
               wpnw_tmin_19950630,wpnw_tmin_19960630,wpnw_tmin_19970630,wpnw_tmin_19980630,
               wpnw_tmin_19990630,wpnw_tmin_20000630,wpnw_tmin_20010630,wpnw_tmin_20020630,
               wpnw_tmin_20030630,wpnw_tmin_20040630,wpnw_tmin_20050630,wpnw_tmin_20060630,
               wpnw_tmin_20070630,wpnw_tmin_20080630,wpnw_tmin_20090630,wpnw_tmin_20100630,
               wpnw_tmin_20110630,wpnw_tmin_20120630,wpnw_tmin_20130630,wpnw_tmin_20140630,
               wpnw_tmin_20150630,wpnw_tmin_20160630,wpnw_tmin_20170630,wpnw_tmin_20180630,
               wpnw_tmin_20190630,wpnw_tmin_20200630)

tmin_30yr_0701 <- mean(wpnw_tmin_19910701,wpnw_tmin_19920701,wpnw_tmin_19930701,wpnw_tmin_19940701,
               wpnw_tmin_19950701,wpnw_tmin_19960701,wpnw_tmin_19970701,wpnw_tmin_19980701,
               wpnw_tmin_19990701,wpnw_tmin_20000701,wpnw_tmin_20010701,wpnw_tmin_20020701,
               wpnw_tmin_20030701,wpnw_tmin_20040701,wpnw_tmin_20050701,wpnw_tmin_20060701,
               wpnw_tmin_20070701,wpnw_tmin_20080701,wpnw_tmin_20090701,wpnw_tmin_20100701,
               wpnw_tmin_20110701,wpnw_tmin_20120701,wpnw_tmin_20130701,wpnw_tmin_20140701,
               wpnw_tmin_20150701,wpnw_tmin_20160701,wpnw_tmin_20170701,wpnw_tmin_20180701,
               wpnw_tmin_20190701,wpnw_tmin_20200701)

tmin_30yr_0702 <- mean(wpnw_tmin_19910702,wpnw_tmin_19920702,wpnw_tmin_19930702,wpnw_tmin_19940702,
               wpnw_tmin_19950702,wpnw_tmin_19960702,wpnw_tmin_19970702,wpnw_tmin_19980702,
               wpnw_tmin_19990702,wpnw_tmin_20000702,wpnw_tmin_20010702,wpnw_tmin_20020702,
               wpnw_tmin_20030702,wpnw_tmin_20040702,wpnw_tmin_20050702,wpnw_tmin_20060702,
               wpnw_tmin_20070702,wpnw_tmin_20080702,wpnw_tmin_20090702,wpnw_tmin_20100702,
               wpnw_tmin_20110702,wpnw_tmin_20120702,wpnw_tmin_20130702,wpnw_tmin_20140702,
               wpnw_tmin_20150702,wpnw_tmin_20160702,wpnw_tmin_20170702,wpnw_tmin_20180702,
               wpnw_tmin_20190702,wpnw_tmin_20200702)

tmin_30yr_0703 <- mean(wpnw_tmin_19910703,wpnw_tmin_19920703,wpnw_tmin_19930703,wpnw_tmin_19940703,
               wpnw_tmin_19950703,wpnw_tmin_19960703,wpnw_tmin_19970703,wpnw_tmin_19980703,
               wpnw_tmin_19990703,wpnw_tmin_20000703,wpnw_tmin_20010703,wpnw_tmin_20020703,
               wpnw_tmin_20030703,wpnw_tmin_20040703,wpnw_tmin_20050703,wpnw_tmin_20060703,
               wpnw_tmin_20070703,wpnw_tmin_20080703,wpnw_tmin_20090703,wpnw_tmin_20100703,
               wpnw_tmin_20110703,wpnw_tmin_20120703,wpnw_tmin_20130703,wpnw_tmin_20140703,
               wpnw_tmin_20150703,wpnw_tmin_20160703,wpnw_tmin_20170703,wpnw_tmin_20180703,
               wpnw_tmin_20190703,wpnw_tmin_20200703)

#subtraction function
anomCalc <- function(x, y) {
  return(x - y)
}
#manually substract the norms from the 2021 dailies to make anomaly maps for 2021
tmin_anom_20210624 <- raster::overlay(wpnw_tmin_20210624,tmin_30yr_0624,fun = anomCalc)
tmin_anom_20210625 <- raster::overlay(wpnw_tmin_20210625,tmin_30yr_0625,fun = anomCalc)
tmin_anom_20210626 <- raster::overlay(wpnw_tmin_20210626,tmin_30yr_0626,fun = anomCalc)
tmin_anom_20210627 <- raster::overlay(wpnw_tmin_20210627,tmin_30yr_0627,fun = anomCalc)
tmin_anom_20210628 <- raster::overlay(wpnw_tmin_20210628,tmin_30yr_0628,fun = anomCalc)
tmin_anom_20210629 <- raster::overlay(wpnw_tmin_20210629,tmin_30yr_0629,fun = anomCalc)
tmin_anom_20210630 <- raster::overlay(wpnw_tmin_20210630,tmin_30yr_0630,fun = anomCalc)
tmin_anom_20210701 <- raster::overlay(wpnw_tmin_20210701,tmin_30yr_0701,fun = anomCalc)
tmin_anom_20210702 <- raster::overlay(wpnw_tmin_20210702,tmin_30yr_0702,fun = anomCalc)
tmin_anom_20210703 <- raster::overlay(wpnw_tmin_20210703,tmin_30yr_0703,fun = anomCalc)

zlim <- c(-3,20)
# set same raster limits and compared adjacent days. 062921 is definitely the warmest anomaly
plot(tmin_anom_20210629,zlim=zlim)
#0626 - 0701 is really the heat dome period of interest for this anomaly plots
#it's really a toss-up whether 0628 or 0629 is the warmer day for the tmin anomaly. Except for the Mt Bachelor area it seems like 0629 had the greater anomaly. It might be prudent to calculate stats for the ZPS in these regions. Tmax seems to have the biggest anomaly on 062921.
writeRaster(tmin_anom_20210628, filename="tmin_anom_20210628.bil", format="EHdr", overwrite=FALSE)
writeRaster(tmin_anom_20210629, filename="tmin_anom_20210629.bil", format="EHdr", overwrite=FALSE)

#041822 - looking at a way to do it with a list but I'll put that aside for now.
mapply(function(x, y) x(y), fun_list, arg_list)

#042022 - doing the same anomaly map construction but for tmean
ls()
#clear memory of a bunch of rasters
rm(list=ls()[400:616])
#iterated this process a bunch to remove some more rasters from memory

prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean")
get_prism_dailys(type = "tmean", minDate = "1991-06-27", maxDate = "1991-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1992-06-27", maxDate = "1992-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1993-06-27", maxDate = "1993-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1994-06-27", maxDate = "1994-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1995-06-27", maxDate = "1995-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1996-06-27", maxDate = "1996-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1997-06-27", maxDate = "1997-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1998-06-27", maxDate = "1998-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "1999-06-27", maxDate = "1999-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2000-06-27", maxDate = "2000-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2001-06-27", maxDate = "2001-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2002-06-27", maxDate = "2002-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2003-06-27", maxDate = "2003-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2004-06-27", maxDate = "2004-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2005-06-27", maxDate = "2005-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2006-06-27", maxDate = "2006-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2007-06-27", maxDate = "2007-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2008-06-27", maxDate = "2008-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2009-06-27", maxDate = "2009-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2010-06-27", maxDate = "2010-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2011-06-27", maxDate = "2011-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2012-06-27", maxDate = "2012-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2013-06-27", maxDate = "2013-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2014-06-27", maxDate = "2014-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2015-06-27", maxDate = "2015-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2016-06-27", maxDate = "2016-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2017-06-27", maxDate = "2017-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2018-06-27", maxDate = "2018-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2019-06-27", maxDate = "2019-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2020-06-27", maxDate = "2020-07-01", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2021-06-27", maxDate = "2021-07-01", keepZip = FALSE)

crs(wpnw) <- crs(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210629_bil\\PRISM_tmean_stable_4kmD2_20210629_bil.bil"))

wpnw_list = c()
UStmean<-pd_to_file(prism_archive_ls())

#I'm finding the list weird to work with. Switching to just making the raster objects I need
for (i in 1:length(UStmean)){
    assign(paste0("wpnw_tmean_",substr(UStmean[i],134,141)),crop(raster(UStmean[i]),wpnw))
    }

#manually calculating daily 30yr norms from 1991-2020
tmean_30yr_0627 <- mean(wpnw_tmean_19910627,wpnw_tmean_19920627,wpnw_tmean_19930627,wpnw_tmean_19940627,
               wpnw_tmean_19950627,wpnw_tmean_19960627,wpnw_tmean_19970627,wpnw_tmean_19980627,
               wpnw_tmean_19990627,wpnw_tmean_20000627,wpnw_tmean_20010627,wpnw_tmean_20020627,
               wpnw_tmean_20030627,wpnw_tmean_20040627,wpnw_tmean_20050627,wpnw_tmean_20060627,
               wpnw_tmean_20070627,wpnw_tmean_20080627,wpnw_tmean_20090627,wpnw_tmean_20100627,
               wpnw_tmean_20110627,wpnw_tmean_20120627,wpnw_tmean_20130627,wpnw_tmean_20140627,
               wpnw_tmean_20150627,wpnw_tmean_20160627,wpnw_tmean_20170627,wpnw_tmean_20180627,
               wpnw_tmean_20190627,wpnw_tmean_20200627)

tmean_30yr_0628 <- mean(wpnw_tmean_19910628,wpnw_tmean_19920628,wpnw_tmean_19930628,wpnw_tmean_19940628,
               wpnw_tmean_19950628,wpnw_tmean_19960628,wpnw_tmean_19970628,wpnw_tmean_19980628,
               wpnw_tmean_19990628,wpnw_tmean_20000628,wpnw_tmean_20010628,wpnw_tmean_20020628,
               wpnw_tmean_20030628,wpnw_tmean_20040628,wpnw_tmean_20050628,wpnw_tmean_20060628,
               wpnw_tmean_20070628,wpnw_tmean_20080628,wpnw_tmean_20090628,wpnw_tmean_20100628,
               wpnw_tmean_20110628,wpnw_tmean_20120628,wpnw_tmean_20130628,wpnw_tmean_20140628,
               wpnw_tmean_20150628,wpnw_tmean_20160628,wpnw_tmean_20170628,wpnw_tmean_20180628,
               wpnw_tmean_20190628,wpnw_tmean_20200628)

tmean_30yr_0629 <- mean(wpnw_tmean_19910629,wpnw_tmean_19920629,wpnw_tmean_19930629,wpnw_tmean_19940629,
               wpnw_tmean_19950629,wpnw_tmean_19960629,wpnw_tmean_19970629,wpnw_tmean_19980629,
               wpnw_tmean_19990629,wpnw_tmean_20000629,wpnw_tmean_20010629,wpnw_tmean_20020629,
               wpnw_tmean_20030629,wpnw_tmean_20040629,wpnw_tmean_20050629,wpnw_tmean_20060629,
               wpnw_tmean_20070629,wpnw_tmean_20080629,wpnw_tmean_20090629,wpnw_tmean_20100629,
               wpnw_tmean_20110629,wpnw_tmean_20120629,wpnw_tmean_20130629,wpnw_tmean_20140629,
               wpnw_tmean_20150629,wpnw_tmean_20160629,wpnw_tmean_20170629,wpnw_tmean_20180629,
               wpnw_tmean_20190629,wpnw_tmean_20200629)

tmean_30yr_0630 <- mean(wpnw_tmean_19910630,wpnw_tmean_19920630,wpnw_tmean_19930630,wpnw_tmean_19940630,
               wpnw_tmean_19950630,wpnw_tmean_19960630,wpnw_tmean_19970630,wpnw_tmean_19980630,
               wpnw_tmean_19990630,wpnw_tmean_20000630,wpnw_tmean_20010630,wpnw_tmean_20020630,
               wpnw_tmean_20030630,wpnw_tmean_20040630,wpnw_tmean_20050630,wpnw_tmean_20060630,
               wpnw_tmean_20070630,wpnw_tmean_20080630,wpnw_tmean_20090630,wpnw_tmean_20100630,
               wpnw_tmean_20110630,wpnw_tmean_20120630,wpnw_tmean_20130630,wpnw_tmean_20140630,
               wpnw_tmean_20150630,wpnw_tmean_20160630,wpnw_tmean_20170630,wpnw_tmean_20180630,
               wpnw_tmean_20190630,wpnw_tmean_20200630)

tmean_30yr_0701 <- mean(wpnw_tmean_19910701,wpnw_tmean_19920701,wpnw_tmean_19930701,wpnw_tmean_19940701,
               wpnw_tmean_19950701,wpnw_tmean_19960701,wpnw_tmean_19970701,wpnw_tmean_19980701,
               wpnw_tmean_19990701,wpnw_tmean_20000701,wpnw_tmean_20010701,wpnw_tmean_20020701,
               wpnw_tmean_20030701,wpnw_tmean_20040701,wpnw_tmean_20050701,wpnw_tmean_20060701,
               wpnw_tmean_20070701,wpnw_tmean_20080701,wpnw_tmean_20090701,wpnw_tmean_20100701,
               wpnw_tmean_20110701,wpnw_tmean_20120701,wpnw_tmean_20130701,wpnw_tmean_20140701,
               wpnw_tmean_20150701,wpnw_tmean_20160701,wpnw_tmean_20170701,wpnw_tmean_20180701,
               wpnw_tmean_20190701,wpnw_tmean_20200701)

#subtraction function
anomCalc <- function(x, y) {
  return(x - y)
}
#manually substract the norms from the 2021 dailies to make anomaly maps for 2021
tmean_anom_20210627 <- raster::overlay(wpnw_tmean_20210627,tmean_30yr_0627,fun = anomCalc)
tmean_anom_20210628 <- raster::overlay(wpnw_tmean_20210628,tmean_30yr_0628,fun = anomCalc)
tmean_anom_20210629 <- raster::overlay(wpnw_tmean_20210629,tmean_30yr_0629,fun = anomCalc)
tmean_anom_20210630 <- raster::overlay(wpnw_tmean_20210630,tmean_30yr_0630,fun = anomCalc)
tmean_anom_20210701 <- raster::overlay(wpnw_tmean_20210701,tmean_30yr_0701,fun = anomCalc)

zlim <- c(-5,20)
# set same raster limits and compared adjacent days. 062921 is definitely the warmest anomaly
plot(tmean_anom_20210629,zlim=zlim)
#0628 - 0630 are the hottest in the ZPS for the tmean anomalies
#hard to say which has the greater tmean anomaly but it seems like it might be 062921. This would be good to calculate manually and go from there.

#write rasters to working directory (Documents), but then I manually transfer them to my "writes" folder for this exercise ("C:\Users\luke.reyes\OneDrive - Washington State University (email.wsu.edu)\Snow\TempAnomalies\PRISM_R\writes")
writeRaster(tmean_anom_20210628, filename="tmean_anom_20210628.bil", format="EHdr", overwrite=FALSE)
writeRaster(tmean_anom_20210629, filename="tmean_anom_20210629.bil", format="EHdr", overwrite=FALSE)
writeRaster(tmean_anom_20210630, filename="tmean_anom_20210630.bil", format="EHdr", overwrite=FALSE)

#going to write the SNODAS files for 0401 to netcdf, add them up in R to generate the ZPS in 3 a/b/c ways, write it, visualize a/b/c versions in ArcMap
#042122 - I wrote the files to netcdf per the detailed methods in https://emailwsu-my.sharepoint.com/personal/luke_reyes_wsu_edu/Documents/Snow/Methods.docx
#let's crop the rasters to the extent I need before doing all the math. Then I can cloud the full rasters too
library(ncdf4)
extent(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine\\SWE_20220401.nc"))

#this returns the following: xmin: -124.7338 ; xmax: -66.94208 ; ymin: 24.94958 ; ymax: 52.87458 
snowpnw <- as(extent(-124.7338, -118, 41.5, 50), 'SpatialPolygons')
#assign cropping extent to same coordinate system as one of the rasters (062921 tmax in this case)
crs(snowpnw) <- crs(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine\\SWE_20210401.nc"))
#check results
extent(snowpnw)
crs(snowpnw)
#looks great

#crop a raster
wpnw_swe_040121 <- crop(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine\\SWE_20210401.nc"),snowpnw)
#check by plotting cropped
plot(wpnw_swe_040121)
#this works swimmingly. Time to make a loop that crops all the swe 0401 rasters

#said loop
snowpnw_list = c()
swe0401 <- list.files(path="C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine", pattern="\\.nc$")
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine")
for (i in 1:length(swe0401)){
    snowpnw_list <- append(snowpnw_list, assign(paste0("wpnw_swe_",substr(swe0401[i],5,12)),crop(raster(swe0401[i]),snowpnw)))
    }

#construct zps from reclassified rasters
rcpers39 <- function(x) { ifelse(x >= 39 , 1, ifelse(x < 39, 0, NA)) }
swebin_20040401 <- calc(wpnw_swe_20040401,fun=rcpers39)
swebin_20050401 <- calc(wpnw_swe_20050401,fun=rcpers39)
swebin_20060401 <- calc(wpnw_swe_20060401,fun=rcpers39)
swebin_20070401 <- calc(wpnw_swe_20070401,fun=rcpers39)
swebin_20080401 <- calc(wpnw_swe_20080401,fun=rcpers39)
swebin_20090401 <- calc(wpnw_swe_20090401,fun=rcpers39)
swebin_20100401 <- calc(wpnw_swe_20100401,fun=rcpers39)
swebin_20110401 <- calc(wpnw_swe_20110401,fun=rcpers39)
swebin_20120401 <- calc(wpnw_swe_20120401,fun=rcpers39)
swebin_20130401 <- calc(wpnw_swe_20130401,fun=rcpers39)
swebin_20140401 <- calc(wpnw_swe_20140401,fun=rcpers39)
swebin_20150401 <- calc(wpnw_swe_20150401,fun=rcpers39)
swebin_20160401 <- calc(wpnw_swe_20160401,fun=rcpers39)
swebin_20170401 <- calc(wpnw_swe_20170401,fun=rcpers39)
swebin_20180401 <- calc(wpnw_swe_20180401,fun=rcpers39)
swebin_20190401 <- calc(wpnw_swe_20190401,fun=rcpers39)
swebin_20200401 <- calc(wpnw_swe_20200401,fun=rcpers39)
swebin_20210401 <- calc(wpnw_swe_20210401,fun=rcpers39)
swebin_20220401 <- calc(wpnw_swe_20220401,fun=rcpers39)

binsum_zps.a <- overlay(swebin_20040401,swebin_20060401,swebin_20070401,swebin_20080401,
             swebin_20090401,swebin_20100401,swebin_20110401,swebin_20120401,swebin_20130401,
             swebin_20140401,swebin_20160401,swebin_20170401,swebin_20180401,swebin_20190401,
             swebin_20200401,swebin_20210401, fun=sum)
             
binsum_zps.b <- overlay(swebin_20060401,swebin_20070401,swebin_20080401,
             swebin_20090401,swebin_20100401,swebin_20110401,swebin_20120401,swebin_20130401,
             swebin_20140401,swebin_20160401,swebin_20170401,swebin_20180401,swebin_20190401,
             swebin_20200401,swebin_20210401, fun=sum)

binsum_zps.c <- overlay(swebin_20060401,swebin_20070401,swebin_20080401,
             swebin_20090401,swebin_20100401,swebin_20110401,swebin_20120401,swebin_20130401,
             swebin_20140401,swebin_20160401,swebin_20170401,swebin_20180401,swebin_20190401,
             swebin_20200401,swebin_20210401,swebin_20220401, fun=sum)

#binsum_zps.a where values =16 should be the same zps as in the earlier analysis. However I was to see if the missing values and weird zeroes in 2004 are an issue. So in versions b and c here I also exclude 2004. If adding 2022 doesn't change anything, I might go with that version instead of version b. I think exporting these rasters and looking at them in ArcMap might be a good idea.
#check if I'm in the directory I want to write to
getwd()
writeRaster(binsum_zps.a, filename="binsum_zpsA.nc", format="CDF",overwrite=FALSE)
writeRaster(binsum_zps.b, filename="binsum_zpsB.nc", format="CDF",overwrite=FALSE)
writeRaster(binsum_zps.c, filename="binsum_zpsC.nc", format="CDF",overwrite=FALSE)

#042322 extract or zonal values from some rasters, now that the ZPS_C is defined. I made ZPS using the April 1st rasters from 2004-22, excluding 2004, 2005, 2015, but including 2022. This means it is defined using 16 years still, even though I drop 2004 which was used in the original definitions.
zpsC_r <- raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine\\zpsC_official\\zpsC_n4515y22.bil")
zpsC_shp <- shapefile("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine\\zpsC_official\\zpsC.shp")
zonal(tmean_anom_20210629, zpsC_r, fun=�mean�, digits=7, na.rm=TRUE)
#threw an error, possibly due to crs misalignment?
zpsC_shp_NAD83 <- spTransform(zpsC_shp, crs(tmean_anom_20210629))
#transform the shapefile b/c it's discouraged to distort the raster
extract(tmean_anom_20210629, zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(tmean_anom_20210629, zpsC_shp_NAD83, fun=sd, digits=7, na.rm=TRUE)
#this works great!
                                                      
#at some point apparently I should learn how to use this Simple Features SF library (sf_transform() instead of spTransform()), but it might be unnecessary for now. sp to be discontinued after 2023.


#just doing some quick work to add 062621 to the tmean rasters I have. I need to validate the statement in the paper about 20C days from 0627-30
prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean")
get_prism_dailys(type = "tmean", minDate = "2021-06-25", maxDate = "2021-06-25", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2021-06-26", maxDate = "2021-06-26", keepZip = FALSE)
get_prism_dailys(type = "tmean", minDate = "2021-06-27", maxDate = "2021-07-02", keepZip = FALSE)


extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210625_bil\\PRISM_tmean_stable_4kmD2_20210625_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210626_bil\\PRISM_tmean_stable_4kmD2_20210626_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210627_bil\\PRISM_tmean_stable_4kmD2_20210627_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210628_bil\\PRISM_tmean_stable_4kmD2_20210628_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210629_bil\\PRISM_tmean_stable_4kmD2_20210629_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210630_bil\\PRISM_tmean_stable_4kmD2_20210630_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210701_bil\\PRISM_tmean_stable_4kmD2_20210701_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210702_bil\\PRISM_tmean_stable_4kmD2_20210702_bil.bil"), zpsC_shp_NAD83, fun=mean, digits=7, na.rm=TRUE)

#crop tmean rasters so I can read them in R and get a histogram of the values
getwd()
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\writes")
writeRaster(crop(tmean_anom_20210629,extent(zpsC_shp_NAD83)),filename="tmean_anom_zpsC_20210629.bil", format="EHdr", overwrite=FALSE)
#this didn't work as intended to crop the raster by the exact undulations of the zpsC, instead it cropped based on the minimum rectangle that contained the zpsC. will need to revisit this in the future.

#042422 - trying to plot the raster R for Figure 1
plot(tmean_anom_20210629, breaks=c(-3,0,5,10,15,20), palette="RdYlBu",main="PNW mean temperature anomaly on June 29th, 2021")
plot(zpsC_shp_NAD83, add=TRUE)
#actually this is way trickier than I thought it would be- I decided to just make it in ArcMap, though that was also a pain in the ass.

#extracting info for the minimum temps during the heat dome
prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin")
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210625_bil\\PRISM_tmin_stable_4kmD2_20210625_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210626_bil\\PRISM_tmin_stable_4kmD2_20210626_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210627_bil\\PRISM_tmin_stable_4kmD2_20210627_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210628_bil\\PRISM_tmin_stable_4kmD2_20210628_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210629_bil\\PRISM_tmin_stable_4kmD2_20210629_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210630_bil\\PRISM_tmin_stable_4kmD2_20210630_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210701_bil\\PRISM_tmin_stable_4kmD2_20210701_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmin\\PRISM_tmin_stable_4kmD2_20210702_bil\\PRISM_tmin_stable_4kmD2_20210702_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)

#ditto for the tmaxes
prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax")
get_prism_dailys(type = "tmax", minDate = "2021-06-25", maxDate = "2021-06-25", keepZip = FALSE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210625_bil\\PRISM_tmax_stable_4kmD2_20210625_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210626_bil\\PRISM_tmax_stable_4kmD2_20210626_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210627_bil\\PRISM_tmax_stable_4kmD2_20210627_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210628_bil\\PRISM_tmax_stable_4kmD2_20210628_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210629_bil\\PRISM_tmax_stable_4kmD2_20210629_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210630_bil\\PRISM_tmax_stable_4kmD2_20210630_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210701_bil\\PRISM_tmax_stable_4kmD2_20210701_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
extract(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmax\\PRISM_tmax_stable_4kmD2_20210702_bil\\PRISM_tmax_stable_4kmD2_20210702_bil.bil"), zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)

#ok let's write a loop to extract the SNODAS values and plug them into a data frame
#initialize lists of the variables I care about
RasterID = c()
SWE = c()

#create list of all the files I want to loop through. Let's do the March-August 2021 files first.
Lswe <- list.files("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc", pattern="SWE*")

#set working directory for the list to read out of:
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc")

#loop through and calculate the zonal stats:
for (i in 1:length(Lswe)){
    RasterID[i] <- substr(Lswe[i],12,19)
    SWE[i] <- extract(raster(Lswe[i]),zpsC_shp,fun=mean,na.rm=TRUE)
    }

nSWE <- SWE/max(SWE)
#not using yet but this will combine my lists into a data.frame, which I should write into a csv and then complete in excel.
zpsC_swe_2021test <- data.frame(RasterID, SWE, nSWE)

#create list of all the files I want to loop through. This loop is for the 2011 values.
Lswe <- list.files("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc", pattern="SWE_snodas_2011*")
#set working directory for the list to read out of:
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc")
#loop through and calculate the zonal stats:
for (i in 1:length(Lswe)){
    RasterID[i] <- substr(Lswe[i],12,19)
    SWE[i] <- extract(raster(Lswe[i]),zpsC_shp,fun=mean,na.rm=TRUE)
    }
nSWE <- SWE/max(SWE)
#not using yet but this will combine my lists into a data.frame, which I should write into a csv and then complete in excel.
zpsC_swe_2011 <- data.frame(RasterID, SWE, nSWE)



# something like the below lines works pretty well for doing a count of cells above x threshold in R. The downside is that it requires a dedicated raster object that you read. In theory though, I bet I could write a loop that would continually overwrite that dedicated variable but store the extracted value each time to a list that I could then reference as needed. 
test <- raster(Lswe[117])
test[test[] < 39 ] <- NA
extract(test,zpsC_shp,fun=function(x,...)length(na.omit(x)))
15063

#making a loop through PRISM to do some new calculations/extractions with the zpsC
library(prism)
library(sp)
library(raster)
library(ncdf4)

#set prism directory to work in
prism_set_dl_dir("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean")
#set working directory to write to
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_NetCDF")

#set extent to use for cropping
#create spatial extent polygon to use for cropping
wpnw <- as(extent(-125.0208, -118, 41.5 ,49.9375), 'SpatialPolygons')
#assign cropping extent to same coordinate system as one of the rasters (062921 tmax in this case)
crs(wpnw) <- crs(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\tmean\\PRISM_tmean_stable_4kmD2_20210629_bil\\PRISM_tmean_stable_4kmD2_20210629_bil.bil"))

#set shapefile to use for extracting data
zpsC_shp <- shapefile("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_R\\zpsdefine\\zpsC_official\\zpsC.shp")
#transform the shapefile b/c it's discouraged to distort the raster
zpsC_shp_NAD83 <- spTransform(zpsC_shp, crs(tmean_anom_20210629))


#test on 2021
get_prism_dailys(type = "tmean", minDate = "2021-03-01", maxDate = "2021-08-31", keepZip = FALSE)

#make list of path to just 2021 daily data
tm21.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=2021))

#loop through and crop all 2021 dailies, Mar-Aug. Store mean temp in the zpsC in vectors. Write the cropped files as NetCDFs for later.
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm21.ls)){
    pr <- raster(tm21.ls[i])
    name_nc <- substr(tm21.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }
#this loop takes 5-6 seconds to run per year! amazing!
zpsC_tmean_2021 <- data.frame(pID, pMeanTemp)

#this works fantastically, takes about 12 minutes per year, and converts PRISMs to netCDFs that are only like 137kb. After I do this for every year, I can cloud the PRISM files and just work with the NetCDFs
#the NetCDFs are confirmed to be NAD83, btw
crs(raster("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISM_NetCDF\\wnw_20210715.nc"))

#this needs to be done for all years 1981-2021 (2021 is already done, as shown above)
get_prism_dailys(type = "tmean", minDate = "1981-03-01", maxDate = "2020-08-31", keepZip = FALSE)
# go through and manually delete the months you don't need

#make list of path to daily data for groups of years. Let's do 5 years at a time so they can run for an hour. (each year is ~11-12 minutes per loop)
tm8185.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=1981:1985,mon=3:8))
tm8690.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=1986:1990,mon=3:8))
tm9195.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=1991:1995,mon=3:8))
tm9600.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=1996:2000,mon=3:8))
tm0105.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=2001:2005,mon=3:8))
tm0610.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=2006:2010,mon=3:8))
tm1115.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=2011:2015,mon=3:8))
tm1620.ls <- pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",years=2016:2020,mon=3:8))

#loop through and crop all dailies for each 5 year period, Mar-Aug. Store mean temp in the zpsC in vectors. Write the cropped files as NetCDFs for later.
#5 year period, 1981-1985
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm8185.ls)){
    pr <- raster(tm8185.ls[i])
    name_nc <- substr(tm8185.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_8185 <- data.frame(pID, pMeanTemp)

#next 5 year period, 1986-1990
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm8690.ls)){
    pr <- raster(tm8690.ls[i])
    name_nc <- substr(tm8690.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_8690 <- data.frame(pID, pMeanTemp)

#next 5 year period, 1991-1995
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm9195.ls)){
    pr <- raster(tm9195.ls[i])
    name_nc <- substr(tm9195.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_9195 <- data.frame(pID, pMeanTemp)

#next 5 year period, 1996-2000
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm9600.ls)){
    pr <- raster(tm9600.ls[i])
    name_nc <- substr(tm9600.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_9600 <- data.frame(pID, pMeanTemp)

#next 5 year period, 2001-2005
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm0105.ls)){
    pr <- raster(tm0105.ls[i])
    name_nc <- substr(tm0105.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_0105 <- data.frame(pID, pMeanTemp)

#next 5 year period, 2006-2010
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm0610.ls)){
    pr <- raster(tm0610.ls[i])
    name_nc <- substr(tm0610.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_0610 <- data.frame(pID, pMeanTemp)

#next 5 year period, 2011-2015
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm1115.ls)){
    pr <- raster(tm1115.ls[i])
    name_nc <- substr(tm1115.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_1115 <- data.frame(pID, pMeanTemp)

#next 5 year period, 2016-2020
pID <- c()
pMeanTemp <- c()

for (i in 1:length(tm1620.ls)){
    pr <- raster(tm1620.ls[i])
    name_nc <- substr(tm1620.ls[i],172,179)
    prc <- crop(pr,wpnw)
    pID[i] <- name_nc
    pMeanTemp[i] <- extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
    prc_nc <- writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)
    }

zpsC_tmean_1620 <- data.frame(pID, pMeanTemp)
#loops completed, bitches

write.csv(zpsC_tmean_8185,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean8185.csv")
write.csv(zpsC_tmean_8690,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean8690.csv")
write.csv(zpsC_tmean_9195,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean9195.csv")
write.csv(zpsC_tmean_9600,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean9600.csv")
write.csv(zpsC_tmean_0105,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean0105.csv")
write.csv(zpsC_tmean_0610,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean0610.csv")
write.csv(zpsC_tmean_1115,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean1115.csv")
write.csv(zpsC_tmean_1620,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean1620.csv")
write.csv(zpsC_tmean_2021,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tmean2021.csv")

#just troubleshooting the last 3 files that were corrupted or something and didn't get processed. 
#These were 04251996, 04262009, and 04142011
#for the 04251996 date:
pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="1996-04-25"))
pr <- raster(pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="1996-04-25")))
name_nc <- substr(pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="1996-04-25")),172,179)
prc <- crop(pr,wpnw)
extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)

#for the 04262009 date:
pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="2009-04-26"))
pr <- raster(pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="2009-04-26")))
name_nc <- substr(pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="2009-04-26")),172,179)
prc <- crop(pr,wpnw)
extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)

#for the 04142011 date:
pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="2011-04-14"))
pr <- raster(pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="2011-04-14")))
name_nc <- substr(pd_to_file(prism_archive_subset(type="tmean",temp_period="daily",dates="2011-04-14")),172,179)
prc <- crop(pr,wpnw)
extract(prc,zpsC_shp_NAD83, fun=mean, weights=TRUE, digits=7, na.rm=TRUE)
writeRaster(prc, filename=paste("wnw_",name_nc,".nc",sep=""),format="CDF",overwrite=TRUE)

#done extracting PRISM tmean for the zpsC, as well as writing NetCDFs for each date.
#switchinig to combining the spreadsheets and calculating the average for each day and then getting the anomaly for each day, also adding ENSO information. Making a master spreadsheet to draw from for figure 2a (snodas time-series) and 4 (long-term)

#version of figure 4 with the PRISM data:
library(ggplot2)
library(scales)
library(colorspace)
library(RColorBrewer)

pzpsC5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\PRISMZPSC5Cbyyr.csv",header=T)

pzpsC5Csince93 <- cbind("Year"=pzpsC5Cbyyr[13:41,1],"pDegDayPlus5C_30"=pzpsC5Cbyyr[13:41,2])
summary(lm(data=as.data.frame(pzpsC5Csince93),pDegDayPlus5C_30~Year))
 
# loess text: method=loess,method.args=list(span=1),

#sensitivity analysis of defining the start point of the linear section
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1981:2021){
      SA5CDDrsq.30x[i-1980] <- summary(lm(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30x[i-1980] <- summary(lm(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDs.30x[i-1980] <- summary(lm(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1]))$coefficients[2]
      }

SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDphc3.30x = vector()
SA5CDDs.30x = vector()
for(i in 1981:2021){
      SA5CDDrsq.30x[i-1980] <- summary(lm_robust(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1],se_type="HC3"))$r.squared
      SA5CDDp.30x[i-1980] <- summary(lm(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDphc3.30x[i-1980] <- summary(lm_robust(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[8]
      SA5CDDs.30x[i-1980] <- summary(lm_robust(subset(pzpsC5Cbyyr,Year>=i)[,2]~subset(pzpsC5Cbyyr,Year>=i)[,1],se_type="HC3"))$coefficients[2]
      }


pszSA5CDD.30x <- data.frame("Year"=seq(1981,2021),"Pval"=SA5CDDp.30x,"R2"=SA5CDDrsq.30x,"Slopes"=SA5CDDs.30x,"Pval_HC3"=SA5CDDphc3.30x,"Station"=rep("Persistent Snow Zone (PRISM); Fig. 4(a)",length(SA5CDDs.30x)))


plot(seq(1981,2021),SA5CDDrsq.30x,xlim=c(1981,2021),ylim=c(0,1))
plot(seq(1981,2021),SA5CDDp.30x,xlim=c(1981,2021),ylim=c(0,1))
plot(seq(1981,2021),SA5CDDs.30x,xlim=c(1981,2015),ylim=c(0,10))

#loess version of PRISM anomalies sum:                   
pDegDayPlus5Canomslo = ggplot(pzpsC5Cbyyr,aes(x=Year,y=pDegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(pzpsC5Cbyyr),aes(x=Year,y=pDegDayPlus5C_30),method=loess,method.args=list(span=1), color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSOoni),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(pDegDayPlus5C_30>125,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-3,nudge_x=0,size=3.5)+
   annotate("text",x=2012.85,y=6,label="2011",size=3.5)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="Summed daily anomalies \u2265 5\u00b0C during AMJ period annually")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1981,2021),breaks=c(1981,1985,1990,1995,2000,2005,2010,2015,2021))+
   scale_y_continuous(limits=c(0,200),breaks=c(0,50,100,150,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
pDegDayPlus5Canomslo

#same figure but with lm method
pDegDayPlus5Canomslm = ggplot(pzpsC5Cbyyr,aes(x=Year,y=pDegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(pzpsC5Csince93),aes(x=Year,y=pDegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
   geom_point(aes(fill=ENSOoni),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(pDegDayPlus5C_30>125,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-3,nudge_x=0,size=3.5)+
   annotate("text",x=2012.85,y=6,label="2011",size=3.5)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="(a) Summed daily anomalies \u2265 5\u00b0C during AMJ period annually")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1981,2021),breaks=c(1981,1985,1990,1995,2000,2005,2010,2015,2021))+
   scale_y_continuous(limits=c(0,200),breaks=c(0,50,100,150,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
pDegDayPlus5Canomslm

#now the paradise ranger station:
##repeating analysis for a different station - Paradise Ranger Station, which goes back until December 1916
prsall <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\ParadiseRSHistoricalDaily1621.csv",header=T)

PRSDegDayPlus5C_30 = vector()
PRSDayCountPlus5C_30 = vector()

for(i in 1917:2021){
      PRSDegDayPlus5C_30[i-1916] <- sum(subset(subset(subset(prsall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5)$AnomTempC)
      PRSDayCountPlus5C_30[i-1916] <- nrow(subset(subset(subset(prsall,Month==4|Month==5|Month==6),Year==i),AnomTempC>5))
      }

prs5Cbyyr = data.frame(Year=seq(1917,2021), PRSDegDayPlus5C_30, PRSDayCountPlus5C_30)
prs5Cbyyr$PRSDegExpOver5C_30 <- prs5Cbyyr$PRSDegDayPlus5C_30 - (5*PRSDayCountPlus5C_30)

#wrote it to a csv so I could add the ENSO data manually
write.csv(prs5Cbyyr,"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\prs5Cbyyr.csv")

#NOTE THAT ENSO HAS A 2.5 VALUE FOR 2016 - THIS IS ACCURATE TO THE DATA BUT FOR GRAPHICAL PURPOSES I THINK IT IS REASONABLE TO CUT IT TO 2, SINCE THAT'S STILL AN INCREDIBLY STRONG EL NINO, AND OTHERWISE 2016 IS THE SOLO +2.5 AND IT THROWS OFF THE LEGEND SCALE
prs5Cbyyr <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\TempAnomalies\\prs5Cbyyr.csv",header=T)
prs5Cbyyr$ENSO[100] <- 2
#THIS ADJUSTS THE 2.5 TO 2

summary(lm(data=as.data.frame(prs5Cbyyr),PRSDegDayPlus5C_30~Year))
ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegDayPlus5C_30,label=Year),na.rm=F) + geom_point()
ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegExpOver5C_30,label=Year),na.rm=F) + geom_point()

prs5Csince93 <- cbind("Year"=prs5Cbyyr[77:105,1],"PRSDegDayPlus5C_30"=prs5Cbyyr[77:105,2])
summary(lm(data=as.data.frame(prs5Csince93),PRSDegDayPlus5C_30~Year))
 
#sensitivity analysis of defining the start point of the linear section
SA5CDDrsq.30x = vector()
SA5CDDp.30x = vector()
SA5CDDs.30x = vector()
for(i in 1917:2021){
      SA5CDDrsq.30x[i-1916] <- summary(lm(subset(prs5Cbyyr,Year>=i)[,2]~subset(prs5Cbyyr,Year>=i)[,1]))$r.squared
      SA5CDDp.30x[i-1916] <- summary(lm(subset(prs5Cbyyr,Year>=i)[,2]~subset(prs5Cbyyr,Year>=i)[,1]))$coefficients[8]
      SA5CDDs.30x[i-1916] <- summary(lm(subset(prs5Cbyyr,Year>=i)[,2]~subset(prs5Cbyyr,Year>=i)[,1]))$coefficients[2]
      }

plot(seq(1917,2021),SA5CDDrsq.30x,xlim=c(1917,2021),ylim=c(0,1))
#interesting, another big spike in R2 at 1993
plot(seq(1917,2021),SA5CDDp.30x,xlim=c(1917,2021),ylim=c(0,1))
abline(a=0.05,b=0)
plot(seq(1917,2021),SA5CDDs.30x,xlim=c(1917,2015))


#loess version of paradise ranger station anomalies sum - it is pretty meh, don't bother plotting it.
prsDegDayPlus5Canomslo = ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(prs5Cbyyr),aes(x=Year,y=PRSDegDayPlus5C_30),method=loess,method.args=list(span=1), color="black",fill="grey20",alpha=0.2,size=0.5)+
      geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(PRSDegDayPlus5C_30>150,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-3,nudge_x=0,size=3.5)+
   annotate("text",x=2012.85,y=6,label="2011",size=3.5)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="Summed daily anomalies \u2265 5\u00b0C during AMJ period annually")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1917,2021),breaks=c(1917,1925,1935,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,275),breaks=c(0,50,100,150,200,250,275),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
prsDegDayPlus5Canomslo

#same figure but with lm method. 1100 by 450 pixels in RStudio
prsDegDayPlus5Canomslm = ggplot(prs5Cbyyr,aes(x=Year,y=PRSDegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(prs5Csince93),aes(x=Year,y=PRSDegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
   geom_point(aes(fill=ENSO),size=3.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(PRSDegDayPlus5C_30>150,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-3,nudge_x=0,size=3.5)+
   annotate("text",x=2012.85,y=6,label="2011",size=3.5)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title="Summed daily anomalies \u2265 5\u00b0C during AMJ period annually")+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1917,2021),breaks=c(1917,1925,1935,1945,1955,1965,1975,1985,1995,2005,2015,2021))+
   scale_y_continuous(limits=c(0,275),breaks=c(0,50,100,150,200,250,275),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),plot.title=element_text(size=14), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.5,"cm"),legend.key.height=unit(1.5,"cm"),legend.text=element_text(size=10),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
prsDegDayPlus5Canomslm

#raster slope project
#to start - need the average daily raster for April 1 - June 30 for years 1991 - 2020
setwd("C:/Users/luke.reyes/OneDrive - Washington State University (email.wsu.edu)/Snow/TempAnomalies/PRISM_NetCDF")
#since the wd is set to where the netcdfs are stored, I can just use "filename.nc" to access the rasters I need
#trial run on 0401 rasters
#get list of the rasters I need to average
tmean_nclist <- list.files(pattern=c("*04...nc|*05...nc|*06...nc"))[911:3640]
#creates list of 2730 items, all the days I want to average across the years
for (i in 1:91){
        rstk <- stack(tmean_nclist[seq(i,2730,91)])
        dayn <- substr(tmean_nclist[seq(i,2730,91)][1],9,12)
        rstkmn <- writeRaster(mean(rstk),filename=paste("wnw_",dayn,"_tmean.nc",sep=""), format="CDF", overwrite=FALSE)
    }
#loop that calculates and writes the tmean normal for each AMJ date by averaging that day across 1991-2020 (30 years)

#052321 - repeating this on the March and July days that bookend AMJ, so that I can do a 7-day moving average of the rasters and use those as the daily means
setwd("C:/Users/luke.reyes/OneDrive - Washington State University (email.wsu.edu)/Snow/TempAnomalies/PRISM_NetCDF")
tmean_nclist <- list.files(pattern=c("*032..nc|*033..nc|*070..nc"))[211:840]
#creates list of 630 items - 21*30 = 630
for (i in 1:21){
        rstk <- stack(tmean_nclist[seq(i,630,21)])
        dayn <- substr(tmean_nclist[seq(i,630,21)][1],9,12)
        rstkmn <- writeRaster(mean(rstk),filename=paste("wnw_",dayn,"_tmean.nc",sep=""), format="CDF", overwrite=FALSE)
    }
#done in about a minute or maybe less

tmean_nclist <- list.files(pattern=c("*tmean.nc"))
#112 item list, with April 1 being item 13 and June 30 being item 103
for (i in 13:103){
    rstk <- stack(tmean_nclist[(i-3):(i+3)])
    dayn <- substr(tmean_nclist[i],5,8)
    rstkmn <- writeRaster(mean(rstk),filename=paste("wnw_",dayn,"_tmean7ma.nc",sep=""), format="CDF", overwrite=FALSE)
    }
#the [i] in dayn makes it grab the numbers in the filename "wnw_####_tmean.nc" to assign the correct date
#this works fantastic and wrote everything in just a minute or less

#to compile +5C anomalies for each year:
blankr <- rstkmn - rstkmn
AMJanomr <- blankr
#initialize a blank raster to hold all the future rasters
AMJdayslist <- list.files(pattern=c("wnw_....04|wnw_....05|wnw_....06"))
AMJnormlist <- list.files(pattern=c("*tmean7ma.nc"))
for (i in 0:40){
    for (j in 1:91){
        dayanom <- raster(AMJdayslist[(i*91)+j]) - raster(AMJnormlist[j])
        dayanom[dayanom[] < 5 ] <- 0
        AMJanomr <- dayanom + AMJanomr
        yrn <- 1981+i
        if(j==91){
             writeRaster(AMJanomr,filename=paste("wnw_",yrn,"_AMJ+5Ctmeananom.nc",sep=""), format="CDF", overwrite=FALSE)
             AMJanomr <- blankr
                  }
        }
    }


#clear out some rasters I don't need to keep in memory atm
ls()
rm(list=ls()[434:650])


#now that I have a raster for each year, let's do a regression through the full stack and starting in 1993
AMJanombyyr_list <- list.files(pattern="*Ctmeananom.nc")
rstk <- stack(AMJanombyyr_list)
library(spatialEco)
library(EnvStats)
regr81 <- raster.kendall(rstk, p.value=TRUE,z.value=TRUE,intercept=TRUE,confidence=TRUE,tau=TRUE)
#succesfully makes a raster brick where each raster is composed of grid cells which have the value of each parameter
#repeat for 1993 as the start year:
rstk <- stack(AMJanombyyr_list[13:41])
regr93 <- raster.kendall(rstk, p.value=TRUE,z.value=TRUE,intercept=TRUE,confidence=TRUE,tau=TRUE)
#repeat for 1991 as the start year:
rstk <- stack(AMJanombyyr_list[11:41])
regr91 <- raster.kendall(rstk, p.value=TRUE,z.value=TRUE,intercept=TRUE,confidence=TRUE,tau=TRUE)

writeRaster(regr81[[7]],filename="wnw_8121_AMJ+5Ctmeananom_tau.nc", format="CDF", overwrite=FALSE)
wpnwsmall <- as(extent(-125.0208, -119.6, 41.88 ,49.065), 'SpatialPolygons')
#assign cropping extent to same coordinate system as one of the rasters (062921 tmax in this case)
crs(wpnwsmall) <- crs(wpnw)
#check results
extent(wpnwsmall)
#looks great
#crop a raster
test <- crop(raster(regr93[[7]]),wpnwsmall)
writeRaster(test,filename="wnw_t_9321_AMJ+5Ctmeananom_tau.nc", format="CDF", overwrite=FALSE)


#same as above for the +5C, but let's just do for all the anomalies
blankr <- rstkmn - rstkmn
AMJanomr <- blankr
#initialize a blank raster to hold all the future rasters
AMJdayslist <- list.files(pattern=c("wnw_....04|wnw_....05|wnw_....06"))
AMJnormlist <- list.files(pattern=c("*tmean7ma.nc"))
for (i in 0:40){
    for (j in 1:91){
        dayanom <- raster(AMJdayslist[(i*91)+j]) - raster(AMJnormlist[j])
        AMJanomr <- dayanom + AMJanomr
        yrn <- 1981+i
        if(j==91){
             writeRaster(AMJanomr,filename=paste("wnw_",yrn,"_AMJalltmeananom.nc",sep=""), format="CDF", overwrite=FALSE)
             AMJanomr <- blankr
                  }
        }
    }
#now that I have a raster for each year, let's do a regression through the full stack and starting in 1993
AMJallanombyyr_list <- list.files(pattern="*alltmeananom.nc")
rstk <- stack(AMJallanombyyr_list)
library(spatialEco)
library(EnvStats)
regr81all <- raster.kendall(rstk, p.value=TRUE,z.value=TRUE,intercept=TRUE,confidence=TRUE,tau=TRUE)
plot(regr81all)
writeRaster(regr81all[[7]],filename="wnw_8121_AMJalltmeananom_tau.nc", format="CDF", overwrite=FALSE)


#succesfully makes a raster brick where each raster is composed of grid cells which have the value of each parameter
#repeat for 1993 as the start year:
rstk <- stack(AMJallanombyyr_list[13:41])
regr93 <- raster.kendall(rstk, p.value=TRUE,z.value=TRUE,intercept=TRUE,confidence=TRUE,tau=TRUE)
#repeat for 1991 as the start year:
rstk <- stack(AMJanombyyr_list[11:41])
regr91 <- raster.kendall(rstk, p.value=TRUE,z.value=TRUE,intercept=TRUE,confidence=TRUE,tau=TRUE)

writeRaster(regr81[[7]],filename="wnw_8121_AMJ+5Ctmeananom_tau.nc", format="CDF", overwrite=FALSE)
wpnwsmall <- as(extent(-125.0208, -119.6, 41.88 ,49.065), 'SpatialPolygons')
#assign cropping extent to same coordinate system as one of the rasters (062921 tmax in this case)
crs(wpnwsmall) <- crs(wpnw)
#check results
extent(wpnwsmall)
#looks great
#crop a raster
test <- crop(raster(regr93[[7]]),wpnwsmall)
writeRaster(test,filename="wnw_t_9321_AMJ+5Ctmeananom_tau.nc", format="CDF", overwrite=FALSE)



## code for extracting the daily average SWE values for each year. just change the year number in the Lswe object list.file line, and also the write.csv line
#set working directory for the list to read out of:
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc")

Lswe <- list.files("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc", pattern="SWE_snodas_2013")

RasterID <- c()
SWE <- c()
#loop through and calculate the zonal stats:
for (i in 1:length(Lswe)){
    RasterID[i] <- substr(Lswe[i],12,19)
    SWE[i] <- extract(raster(Lswe[i]),zpsC_shp,fun=mean,na.rm=TRUE)
    }
nSWE <- SWE/max(SWE)
#not using yet but this will combine my lists into a data.frame, which I should write into a csv and then complete in excel.
zpsC_SWE_csv <- write.csv(data.frame(RasterID, SWE, nSWE),"C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_SWE_13.csv")

#060122 work
ls()
rm(list=ls()[415:631])
setwd("C:/Users/luke.reyes/OneDrive - Washington State University (email.wsu.edu)/Snow/TempAnomalies/PRISM_NetCDF")


#random calculations to get factoids of interest


## 071822 - seems like maybe some lines are a bit missing or out of order. : /  For now trying to get well-noted code written to construct the figures in a final draft, plus several supplementary figures
#Figures to still do as of today: Supplemental Fig 1, a series of rasters of the heat dome and how it progressed from 6/26-7/1; Fig 2, redo with new SWE calculated with zpsC back when you did that; Supplemental Fig 3a - SWE not normalized but shown as in Fig 2; Supplemental Fig 3b - snow-covered area for 2021 (and other years if easy enough, same style as SupFig3 and Fig2); Fig 3b and 3c - scatter of 2015 or 2016 and 2011 to add to the 2021 temp-SWE % loss scatter; Supplemental Fig 4 - more station trend lines, especially should include a long-term record from Seattle somehow.

#calculating snow-covered area >5mm
library(sp)
library(raster)
library(ncdf4)
library(ggplot2)
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc")

#example of SCA calculation for 2021
Lswe <- list.files("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc", pattern="SWE_snodas_2021")
RasterID <- c()
SCA_5mm <- c()

for (i in 1:length(Lswe)){
    RasterID[i] <- substr(Lswe[i],12,19)
    loopras <- raster(Lswe[i])
    loopras[loopras[]<5] <- NA
    loopras <- loopras/loopras
    SCA_5mm[i] <- extract(loopras,zpsC_shp,fun=sum,na.rm=TRUE)
    }
SCA_pct <- (SCA_5mm/51235)*100
zpsC_SCA5_csv <- write.csv(data.frame(RasterID, SCA_5mm, SCA_pct), "C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_SCA5_21.csv")

#now for the other years (excluding 2004, 2005, 2015?) - modify this code in the first and last lines to customize for year (ie Lswe and write.csv)
Lswe <- list.files("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc", pattern="SWE_snodas_2004")
RasterID <- c()
SCA_5mm <- c()
for (i in 1:length(Lswe)){
    RasterID[i] <- substr(Lswe[i],12,19)
    loopras <- raster(Lswe[i])
    loopras[loopras[]<5] <- NA
    loopras <- loopras/loopras
    SCA_5mm[i] <- extract(loopras,zpsC_shp,fun=sum,na.rm=TRUE)
    }
SCA_pct <- (SCA_5mm/51235)*100
zpsC_SCA5_csv <- write.csv(data.frame(RasterID, SCA_5mm, SCA_pct), "C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_SCA5_04.csv")

#This above loop worked great. I manually appended everything in Excel once I had the individual year csvs. I also interpolated, in the combined table, the missing dates (reference ExtractionLog.xlsx in SNODASdata folder and the readme.txt in the ZS_csvs folder)

#Rather than do the loopras/loopras and then fun=sum workaround, you could use this code to find SCA:
# something like the below lines works pretty well for doing a count of cells above x threshold in R. The downside is that it requires a dedicated raster object that you read.
test <- raster(Lswe[117])
test[test[] < 39 ] <- NA
extract(test,zpsC_shp,fun=function(x,...)length(na.omit(x)))
15063

#Rebuilding the SWE figures using the zpsC data. This is based on code above from around line 630.
#072722 - #SWEtimeseries

#load master table of all data for the SWEtimeseries figure.
zpsC_master <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tm_swe_Master.csv",header=T)

#parse out the melt curves
zpsC_melts <- subset(zpsC_master, zpsC_master$Curve=="DEC")
#parse out temps for 2021
zpsC_21tm <- subset(zpsC_master, zpsC_master$Year==2021)

#add columns for the modified temperatures so they are plottable on a secondary axis
zpsC_21tm$mod_TM3MA <- (zpsC_21tm$pMeanTemp3MA*(0.015))+1.075
zpsC_21tm$mod_NAT <- (zpsC_21tm$pNormTMean7MA*(0.015))+1.075

#load necessary library for plotting
library(ggplot2)

#cut and paste and run the code from: https://github.com/csdaw/ggprism/blob/HEAD/R/annotation_ticks.R
#to define the function "annotation_ticks()" that is used below.

#titles object
ttlsnm <- labs(title="SWE and temperature over the melting season", x="Julian Day",y="Proportion of annual maximum SWE")
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1.31,ymax=1.39,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1.23,ymax=1.31,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1.15,ymax=1.23,alpha=0.5,fill="grey10")+
    annotate("text",x=14.5+59,y=1.32,label="+3-5\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=14.5+59,y=1.24,label="+5-10\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=14.5+59,y=1.16,label="+10\u00b0C anomaly\n(Heat Dome)",size=3,hjust=0,vjust=0)+


#build figure. annotate lines are for +3-5C (alpha=0.15), +5-10C (alpha=0.3), and +10C (alpha=0.5) anomalies
dswetmpf <-
ggplot() + 
    annotate("rect",xmin=(46.5+59),xmax=(47.5+59),ymin=.65,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=47.5+59,xmax=50.5+59,ymin=.65,ymax=1.48,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=50.5+59,xmax=51.5+59,ymin=.65,ymax=1.48,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=75.5+59,xmax=78.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=91.5+59,xmax=92.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=92.5+59,xmax=95.5+59,ymin=0,ymax=1.48,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=95.5+59,xmax=96.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=110.5+59,xmax=112.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=112.5+59,xmax=118.5+59,ymin=0,ymax=1.48,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=118.5+59,xmax=122.5+59,ymin=0,ymax=1.48,alpha=0.5,fill="grey10")+
    annotate("rect",xmin=122.5+59,xmax=124.5+59,ymin=0,ymax=1.48,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=124.5+59,xmax=127.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=127.5+59,xmax=128.5+59,ymin=0,ymax=1.48,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=128.5+59,xmax=129.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=131.5+59,xmax=137.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=151.5+59,xmax=152.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=152.5+59,xmax=154.5+59,ymin=0,ymax=1.48,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=154.5+59,xmax=158.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=163.5+59,xmax=164.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=164.5+59,xmax=168.5+59,ymin=0,ymax=1.48,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=168.5+59,xmax=169.5+59,ymin=0,ymax=1.48,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1.35,ymax=1.45,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1.25,ymax=1.35,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1.15,ymax=1.25,alpha=0.5,fill="grey10")+
    annotate("text",x=14.5+59,y=1.37,label="+3-5\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=14.5+59,y=1.27,label="+5-10\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=14.5+59,y=1.17,label="+10\u00b0C anomaly\n(Heat Dome)",size=3,hjust=0,vjust=0)+
    geom_line(data=zpsC_21tm,aes(x=JDay,y=mod_TM3MA,linetype="2021 daily mean \n(3-day moving average)\n"),color="tomato3") +
    geom_point(data=zpsC_21tm,aes(x=JDay,y=mod_TM3MA),color="tomato3",size=0.9) +
    geom_line(data=zpsC_21tm,aes(x=JDay,y=mod_NAT,linetype="30-year climatological mean \n(1991-2020)"),color="tomato3") +
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="Neutral"),aes(x=JDay,y=nSWE,group=Year,color="ENSO Neutral years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="LaNina"),aes(x=JDay,y=nSWE,group=Year,color="La Ni\u00f1a years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="ElNino"),aes(x=JDay,y=nSWE,group=Year,color="El Ni\u00f1o years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2011),aes(x=JDay,y=nSWE,color="2011 (Strong La Ni\u00f1a)"))+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2021), aes(x=JDay,y=nSWE,color="2021"))+
    geom_hline(aes(yintercept=1.075),alpha=0.25) +
    scale_x_continuous(limits=c(60,243),breaks=c(60,91,121,152,182,213,243),expand=c(0,5))+
    scale_y_continuous(limits=c(-0.05,1.5),breaks=seq(0,1,0.1),expand=c(0,0),sec.axis=sec_axis(~ ((.)-1.075)/0.015,name="Temperature (\u00b0C)",breaks=seq(-5,35,5))) + ttlsnm + 
    scale_colour_manual(name="Daily SWE (normalized)",values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO Neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) +
    scale_linetype_manual(name="Temperatures",values=c("2021 daily mean \n(3-day moving average)\n"=1,"30-year climatological mean \n(1991-2020)"=2),guide=guide_legend(override.aes=list(linetype=c(1,2),color="tomato3")))+
    theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12,),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,1,0,0),"mm")),axis.title.y.right=element_text(margin=unit(c(0,0,0,2.5),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),legend.position=c(0.17,0.25),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),panel.border = element_rect(colour = "black", fill=NA, size=2))

library(grid)

dswetmpf
    grid.text("March", x = unit(0.16, "npc"), y = unit(0.05, "npc"))
    grid.text("April", x = unit(0.3, "npc"), y = unit(0.05, "npc"))
    grid.text("May", x = unit(0.435, "npc"), y = unit(0.05, "npc"))
    grid.text("June", x = unit(0.57, "npc"), y = unit(0.05, "npc"))
    grid.text("July", x = unit(0.705, "npc"), y = unit(0.05, "npc"))
    grid.text("August", x = unit(0.84, "npc"), y = unit(0.05, "npc"))
#This figure looks awesome and is now done #SWEtimeseries - 080122
#This figure looks awesome and is now done again #SWEtimeseries - 061523 exported 900x775

#to export:
png("Reyes_EDfig2.png",width=2875,height=2500,res=300)
png("Reyes_Sfig2.png",width=5750,height=5000,res=600)
#then rebuild figure with swetime and grid.text commands
dev.off()

#repeat code to draw the non-normalized version of the SWEtimeseries - 080622

#051723 - commenting out and adjusting/removing lines that are no longer needed or need alteration: per reviewers, the temp axis should not be reversed, and the non-normalized version should be the main figure.

#commented out:
#add columns for the modified temperatures so they are plottable on a secondary axis
zpsC_21tm$moda_TM3MA <- (zpsC_21tm$pMeanTemp3MA*(19))+1200
zpsC_21tm$moda_NAT <- (zpsC_21tm$pNormTMean7MA*(19))+1200

#titles object
ttlsm <- labs(title=bquote(bold("(a)")~" SWE and temperature over the melting season"), x="Julian Day",y="Mean SWE (mm)")

#build figure. annotate lines are for +3-5C (alpha=0.15), +5-10C (alpha=0.3), and +10C (alpha=0.5) anomalies
#to change sec axis to normal, in scale_y_continuous I changed 1610 to 1250, and I changed /-35 to /15 (basically, adjusted slope and intercept in this part: =sec_axis(~ ((.)-intercept)/slope for the intercept and slope of a linear conversion of one set of units to another)
#note that legend position and annotate grey rectangles were all repositioned to accommodate the normal temp axis in this version
swetime <-
ggplot() + 
    annotate("rect",xmin=(46.5+59),xmax=(47.5+59),ymin=0,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=47.5+59,xmax=50.5+59,ymin=0,ymax=1750,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=50.5+59,xmax=51.5+59,ymin=0,ymax=1750,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=75.5+59,xmax=78.5+59,ymin=0,ymax=1750,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=91.5+59,xmax=92.5+59,ymin=0,ymax=1750,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=92.5+59,xmax=95.5+59,ymin=0,ymax=1750,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=95.5+59,xmax=96.5+59,ymin=0,ymax=1750,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=110.5+59,xmax=112.5+59,ymin=0,ymax=1750,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=112.5+59,xmax=118.5+59,ymin=0,ymax=1750,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=118.5+59,xmax=122.5+59,ymin=0,ymax=1750,alpha=0.5,fill="grey10")+
    annotate("rect",xmin=122.5+59,xmax=124.5+59,ymin=0,ymax=1750,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=124.5+59,xmax=127.5+59,ymin=0,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=127.5+59,xmax=128.5+59,ymin=0,ymax=1750,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=128.5+59,xmax=129.5+59,ymin=0,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=131.5+59,xmax=137.5+59,ymin=1200,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=151.5+59,xmax=152.5+59,ymin=1200,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=152.5+59,xmax=154.5+59,ymin=1200,ymax=1750,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=154.5+59,xmax=158.5+59,ymin=1200,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=163.5+59,xmax=164.5+59,ymin=1200,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=164.5+59,xmax=168.5+59,ymin=1200,ymax=1750,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=168.5+59,xmax=169.5+59,ymin=1200,ymax=1750,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1550,ymax=1650,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1450,ymax=1550,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=11+59,xmax=14+59,ymin=1350,ymax=1450,alpha=0.5,fill="grey10")+
    annotate("text",x=14.5+59,y=1575,label="+3-5\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=14.5+59,y=1475,label="+5-10\u00b0C\nanomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=14.5+59,y=1375,label="+10\u00b0C anomaly\n(Heat Dome)",size=3,hjust=0,vjust=0)+
    annotate("text",x=80,y=350,label="2015",size=4,hjust=0,vjust=0)+
    annotate("text",x=97,y=240,label="2005",size=4,hjust=0,vjust=0)+
    geom_line(data=zpsC_21tm,aes(x=JDay,y=moda_TM3MA,linetype="2021 daily mean \n(3-day moving average)\n"),color="tomato3") +
    geom_point(data=zpsC_21tm,aes(x=JDay,y=moda_TM3MA),color="tomato3",size=0.9) +
    geom_line(data=zpsC_21tm,aes(x=JDay,y=moda_NAT,linetype="30-year climatological mean \n(1991-2020)"),color="tomato3") +
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="Neutral"),aes(x=JDay,y=SWE,group=Year,color="ENSO Neutral years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="LaNina"),aes(x=JDay,y=SWE,group=Year,color="La Ni\u00f1a years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="ElNino"),aes(x=JDay,y=SWE,group=Year,color="El Ni\u00f1o years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2011),aes(x=JDay,y=SWE,color="2011 (Strong La Ni\u00f1a)"))+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2021), aes(x=JDay,y=SWE,color="2021"))+
    geom_hline(aes(yintercept=1200),alpha=0.25) +
    scale_x_continuous(limits=c(60,243),breaks=c(60,91,121,152,182,213,243),expand=c(0,5))+
    scale_y_continuous(limits=c(-10,1770),breaks=seq(0,1250,250),expand=c(0,0),sec.axis=sec_axis(~ ((.)-1200)/19,name="Temperature (\u00b0C)",breaks=seq(-5,35,5))) + ttlsm + 
    scale_colour_manual(name="Daily SWE (mm)",values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO Neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) +
    scale_linetype_manual(name="Temperatures",values=c("2021 daily mean \n(3-day moving average)\n"=1,"30-year climatological mean \n(1991-2020)"=2),guide=guide_legend(override.aes=list(linetype=c(1,2),color="tomato3")))+
    theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12,),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,1,0,0),"mm")),axis.title.y.right=element_text(margin=unit(c(0,0,0,2.5),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),legend.position=c(0.85,0.44),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),panel.border = element_rect(colour = "black", fill=NA, size=2))

swetime
    grid.text("March", x = unit(0.165, "npc"), y = unit(0.055, "npc"))
    grid.text("April", x = unit(0.3, "npc"), y = unit(0.055, "npc"))
    grid.text("May", x = unit(0.435, "npc"), y = unit(0.055, "npc"))
    grid.text("June", x = unit(0.57, "npc"), y = unit(0.055, "npc"))
    grid.text("July", x = unit(0.705, "npc"), y = unit(0.055, "npc"))
    grid.text("August", x = unit(0.845, "npc"), y = unit(0.055, "npc"))
#This figure looks awesome and is now done #SWEtimeseries - non-normalized - 080622 - exported as 900x775 pixels

#to export:
png("Fig2a.png",width=2875,height=2500,res=300)
png("Fig2a.png",width=5750,height=5000,res=600)
#then rebuild figure with swetime and grid.text commands
dev.off()

#SCAtime series figure - 080822
#reload table because I added in the SCA columns between making the above figures and now
zpsC_master <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tm_swe_Master.csv",header=T)

#parse out the melt curves
zpsC_melts <- subset(zpsC_master, zpsC_master$SCA_curve=="DEC")
#parse out temps for 2021
zpsC_21tm <- subset(zpsC_master, zpsC_master$Year==2021)

#add columns for the modified temperatures so they are plottable on a secondary axis
zpsC_21tm$modc_TM3MA <- (zpsC_21tm$pMeanTemp3MA*(425))+53000
zpsC_21tm$modc_NAT <- (zpsC_21tm$pNormTMean7MA*(425))+53000

#titles object
ttlssca <- labs(title="Snow-covered area and temperature over the melting season", x="Julian Day",y=bquote("Snow-covered area "~(km^2)))

#build figure. annotate lines are for +3-5C (alpha=0.15), +5-10C (alpha=0.3), and +10C (alpha=0.5) anomalies
scatime <-
ggplot() + 
    annotate("rect",xmin=(46.5+59),xmax=(47.5+59),ymin=27000,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=47.5+59,xmax=50.5+59,ymin=27000,ymax=65000,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=50.5+59,xmax=51.5+59,ymin=27000,ymax=65000,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=75.5+59,xmax=78.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=91.5+59,xmax=92.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=92.5+59,xmax=95.5+59,ymin=0,ymax=65000,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=95.5+59,xmax=96.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=110.5+59,xmax=112.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=112.5+59,xmax=118.5+59,ymin=0,ymax=65000,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=118.5+59,xmax=122.5+59,ymin=0,ymax=65000,alpha=0.5,fill="grey10")+
    annotate("rect",xmin=122.5+59,xmax=124.5+59,ymin=0,ymax=65000,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=124.5+59,xmax=127.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=127.5+59,xmax=128.5+59,ymin=0,ymax=65000,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=128.5+59,xmax=129.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=131.5+59,xmax=137.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=151.5+59,xmax=152.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=152.5+59,xmax=154.5+59,ymin=0,ymax=65000,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=154.5+59,xmax=158.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=163.5+59,xmax=164.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=164.5+59,xmax=168.5+59,ymin=0,ymax=65000,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=168.5+59,xmax=169.5+59,ymin=0,ymax=65000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=3+59,xmax=6+59,ymin=61000,ymax=64000,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=3+59,xmax=6+59,ymin=58000,ymax=61000,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=3+59,xmax=6+59,ymin=55000,ymax=58000,alpha=0.5,fill="grey10")+
    annotate("text",x=6.5+59,y=62000,label="+3-5\u00b0C anomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=6.5+59,y=59000,label="+5-10\u00b0C anomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=6.5+59,y=56000,label="+10\u00b0C anomaly (Heat Dome)",size=3,hjust=0,vjust=0)+
    annotate("text",x=71.5,y=41500,label="2015",size=3.5,hjust=0,vjust=0)+
    geom_line(data=zpsC_21tm,aes(x=JDay,y=modc_TM3MA,linetype="2021 daily mean \n(3-day moving average)\n"),color="tomato3") +
    geom_point(data=zpsC_21tm,aes(x=JDay,y=modc_TM3MA),color="tomato3",size=0.9) +
    geom_line(data=zpsC_21tm,aes(x=JDay,y=modc_NAT,linetype="30-year climatological mean \n(1991-2020)"),color="tomato3") +
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="Neutral"),aes(x=JDay,y=SCA_5mm,group=Year,color="ENSO Neutral years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="LaNina"),aes(x=JDay,y=SCA_5mm,group=Year,color="La Ni\u00f1a years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="ElNino"),aes(x=JDay,y=SCA_5mm,group=Year,color="El Ni\u00f1o years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2011),aes(x=JDay,y=SCA_5mm,color="2011 (Strong La Ni\u00f1a)"))+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2021), aes(x=JDay,y=SCA_5mm,color="2021"))+
    geom_hline(aes(yintercept=53000),alpha=0.25) +
    scale_x_continuous(limits=c(60,243),breaks=c(60,91,121,152,182,213,243),expand=c(0,5))+
    scale_y_continuous(limits=c(-1000,66000),breaks=seq(0,55000,5000),expand=c(0,0),sec.axis=sec_axis(~ ((.)-53000)/425,name="Temperature (\u00b0C)",breaks=seq(-5,35,5))) + ttlssca + 
    scale_colour_manual(name=bquote("Daily Snow-covered area "~(km^2)),values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO Neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) +
    scale_linetype_manual(name="Temperatures",values=c("2021 daily mean \n(3-day moving average)\n"=1,"30-year climatological mean \n(1991-2020)"=2),guide=guide_legend(override.aes=list(linetype=c(1,2),color="tomato3")))+
    theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12,),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,1,0,0),"mm")),axis.title.y.right=element_text(margin=unit(c(0,0,0,2.5),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),legend.position=c(0.17,0.22),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),panel.border = element_rect(colour = "black", fill=NA, size=2))

scatime
    grid.text("March", x = unit(0.19, "npc"), y = unit(0.05, "npc"))
    grid.text("April", x = unit(0.32, "npc"), y = unit(0.05, "npc"))
    grid.text("May", x = unit(0.452, "npc"), y = unit(0.05, "npc"))
    grid.text("June", x = unit(0.584, "npc"), y = unit(0.05, "npc"))
    grid.text("July", x = unit(0.716, "npc"), y = unit(0.05, "npc"))
    grid.text("August", x = unit(0.848, "npc"), y = unit(0.05, "npc"))
#This figure looks awesome and is now done #SWEtimeseries - non-normalized - 080822 - exported as 900x775 pixels.
#reversed temp axis to normal on 061523 and re-exported.

#to export:
png("Reyes_EDfig3.png",width=2875,height=2500,res=300)
png("Reyes_Sfig3.png",width=5750,height=5000,res=600)
#then rebuild figure with scatime and grid.text commands
dev.off()

#081922 - supplemental figure of the SWE loss rate, area-adjusted
#reload table because I added in the SCA columns between making the above figures and now
zpsC_master <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tm_swe_Master.csv",header=T)

#parse out the melt curves
zpsC_melts <- subset(zpsC_master, zpsC_master$Curve=="DEC")
#parse out temps for 2021
zpsC_21tm <- subset(zpsC_master, zpsC_master$Year==2021)

#add columns for the modified temperatures so they are plottable on a secondary axis
zpsC_21tm$modd_TM3MA <- (zpsC_21tm$pMeanTemp3MA*(1.5))+15
zpsC_21tm$modd_NAT <- (zpsC_21tm$pNormTMean7MA*(1.5))+15

#titles object
#103023 - applied bquote to ylab, so as to say mm day^-1, vs mm/day as in the original
ttlsaar <- labs(title="Area-adjusted SWE loss rate and temperature over the melting season", x="Julian Day",y=bquote("Rate of Daily SWE change (mm"~day^-1*"; 3-day moving average)"))

#build figure. annotate lines are for +3-5C (alpha=0.15), +5-10C (alpha=0.3), and +10C (alpha=0.5) anomalies
aartime <-
ggplot() + 
    annotate("rect",xmin=(46.5+59),xmax=(47.5+59),ymin=-45,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=47.5+59,xmax=50.5+59,ymin=-45,ymax=60,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=50.5+59,xmax=51.5+59,ymin=-45,ymax=60,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=75.5+59,xmax=78.5+59,ymin=-45,ymax=60,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=91.5+59,xmax=92.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=92.5+59,xmax=95.5+59,ymin=-125,ymax=60,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=95.5+59,xmax=96.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=110.5+59,xmax=112.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+    
    annotate("rect",xmin=112.5+59,xmax=118.5+59,ymin=-125,ymax=60,alpha=0.3,fill="grey10")+    
    annotate("rect",xmin=118.5+59,xmax=122.5+59,ymin=-125,ymax=60,alpha=0.5,fill="grey10")+
    annotate("rect",xmin=122.5+59,xmax=124.5+59,ymin=-125,ymax=60,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=124.5+59,xmax=127.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=127.5+59,xmax=128.5+59,ymin=-125,ymax=60,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=128.5+59,xmax=129.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=131.5+59,xmax=137.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=151.5+59,xmax=152.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=152.5+59,xmax=154.5+59,ymin=-125,ymax=60,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=154.5+59,xmax=158.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=163.5+59,xmax=164.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=164.5+59,xmax=168.5+59,ymin=-125,ymax=60,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=168.5+59,xmax=169.5+59,ymin=-125,ymax=60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=60+59,xmax=63+59,ymin=-70,ymax=-60,alpha=0.15,fill="grey10")+
    annotate("rect",xmin=60+59,xmax=63+59,ymin=-80,ymax=-70,alpha=0.3,fill="grey10")+
    annotate("rect",xmin=60+59,xmax=63+59,ymin=-90,ymax=-80,alpha=0.5,fill="grey10")+
    annotate("text",x=63.5+59,y=-65,label="+3-5\u00b0C anomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=63.5+59,y=-75,label="+5-10\u00b0C anomaly",size=3,hjust=0,vjust=0)+
    annotate("text",x=63.5+59,y=-87,label="+10\u00b0C anomaly\n(Heat Dome)",size=3,hjust=0,vjust=0)+
    geom_line(data=zpsC_21tm,aes(x=JDay,y=modd_TM3MA,linetype="2021 daily mean \n(3-day moving average)\n"),color="tomato3") +
    geom_point(data=zpsC_21tm,aes(x=JDay,y=modd_TM3MA),color="tomato3",size=0.9) +
    geom_line(data=zpsC_21tm,aes(x=JDay,y=modd_NAT,linetype="30-year climatological mean \n(1991-2020)"),color="tomato3") +
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="Neutral"),aes(x=JDay,y=SWE_loss_areaadjusted_3MA,group=Year,color="ENSO Neutral years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="LaNina"),aes(x=JDay,y=SWE_loss_areaadjusted_3MA,group=Year,color="La Ni\u00f1a years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$ENSOType=="ElNino"),aes(x=JDay,y=SWE_loss_areaadjusted_3MA,group=Year,color="El Ni\u00f1o years"),alpha=0.75)+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2011),aes(x=JDay,y=SWE_loss_areaadjusted_3MA,color="2011 (Strong La Ni\u00f1a)"))+
    geom_line(data=subset(zpsC_melts,zpsC_melts$Year==2021), aes(x=JDay,y=SWE_loss_areaadjusted_3MA,color="2021"))+
    geom_hline(aes(yintercept=0),alpha=0.25) +
    geom_hline(aes(yintercept=15),alpha=0.25) +
    scale_x_continuous(limits=c(60,243),breaks=c(60,91,121,152,182,213,243),expand=c(0,5))+
    scale_y_continuous(limits=c(-125,60),breaks=seq(-120,15,15),expand=c(0,2.5),sec.axis=sec_axis(~ ((.)-15)/1.5,name="Temperature (\u00b0C)",breaks=seq(-5,35,5))) + ttlsaar + 
    scale_colour_manual(name="Years",values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO Neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) +
    scale_linetype_manual(name="Temperatures",values=c("2021 daily mean \n(3-day moving average)\n"=1,"30-year climatological mean \n(1991-2020)"=2),guide=guide_legend(override.aes=list(linetype=c(1,2),color="tomato3")))+
    theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=12,),axis.text.y=element_text(face="bold",size=12),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,1,0,0),"mm")),axis.title.y.right=element_text(margin=unit(c(0,0,0,2.5),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),legend.position=c(0.17,0.23),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),panel.border = element_rect(colour = "black", fill=NA, size=2))

aartime
    grid.text("March", x = unit(0.172, "npc"), y = unit(0.05, "npc"))
    grid.text("April", x = unit(0.307, "npc"), y = unit(0.05, "npc"))
    grid.text("May", x = unit(0.442, "npc"), y = unit(0.05, "npc"))
    grid.text("June", x = unit(0.577, "npc"), y = unit(0.05, "npc"))
    grid.text("July", x = unit(0.712, "npc"), y = unit(0.05, "npc"))
    grid.text("August", x = unit(0.847, "npc"), y = unit(0.05, "npc"))
#This figure looks awesome and is now done #area-adjusted SWE melt rate -081922 - exported as 900x775 pixels
#reversed temp axis to normal on 061523 and re-exported.

png("Reyes_EDfig4.png",width=2875,height=2500,res=300)
png("Reyes_Sfig4.png",width=5750,height=5000,res=600)
#then rebuild with grid.text commands, above
dev.off()

#next figure - #SWETempScatter - 080122
#this figure should already be done, the only thing is also making plots for 2011 and 2015
#going to rebuild it b/c this is easy enough
zpsC_master <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tm_swe_Master.csv",header=T)

#parse out the AMJ days
zpsC_AMJ <- subset(zpsC_master, Month==4|Month==5|Month==6)
#parse out the single years you will plot per plot
zpsC_amj11 <- subset(zpsC_AMJ,Year==2011)
zpsC_amj15 <- subset(zpsC_AMJ,Year==2015)
zpsC_amj21 <- subset(zpsC_AMJ,Year==2021)

#load graphing libraries
library(ggplot2)
library(RColorBrewer)

#build 2021 plot
tmpmlt21f <- 
ggplot(data=zpsC_amj21,aes(x=pAnom3MA,y=nSWEloss3MA,color=DayType))+
     geom_point(size=3) + 
     geom_smooth(data=zpsC_amj21,aes(x=pAnom3MA,y=nSWEloss3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)+
     scale_color_manual(values=c("red","black"))+ 
     labs(title=bquote(bold("(b)")~ "SWE percent loss relationship to 2021 AMJ daily temperature anomalies"), x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)")+
     scale_y_continuous(limits=c(-3,0.5),breaks=seq(-3,0.5,0.5)) +
     scale_x_continuous(limits=c(-8,18),breaks=seq(-5,15,5)) +
     theme(panel.background=element_blank(), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),
     legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "grey30"),
     legend.position=c(0.75,0.85),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),legend.text=element_text(size=12),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
     
tmpmlt21f
#as of 081922, this is the polished version of the figure - looks solid
#061923 - removed elements "axis.text.x=element_text(face="bold",size=14),axis.text.y=element_text(face="bold",size=14),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,2,0,0),"mm")),plot.title=element_text(size=18)," from theme, and exported result in RStudio, 700x700. also added "(b)" to title because of new 3(a) figure added (see tmpaar figure below)
#summary stats on the geom_smooth portion:
summary(lm(data=zpsC_amj21,nSWEloss3MA~pAnom3MA))

#110822 - trying a plot with MJJ for 2011 since melting started later
#parse out the AMJ days
zpsC_MJJ <- subset(zpsC_master, Month==5|Month==6|Month==7)
#parse out the single years you will plot per plot
zpsC_mjj11 <- subset(zpsC_MJJ,Year==2011)
#new dataframe on 110822

#same figure but for 2011.
tmpmlt11f <- 
ggplot(data=zpsC_amj11,aes(x=pAnom3MA,y=nSWEloss3MA))+
     geom_point(size=3,color="black") + 
     geom_smooth(data=zpsC_amj11,aes(x=pAnom3MA,y=nSWEloss3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)+
     labs(title=bquote(bold("(a)")~" SWE percent loss relationship to 2011 AMJ daily temperature anomalies"), x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)")+
     scale_y_continuous(limits=c(-2.05,1.75),breaks=seq(-2,1.75,0.5)) +
     scale_x_continuous(limits=c(-6,2.5),breaks=seq(-5,15,5)) +
     theme(panel.background=element_blank(), axis.text.x=element_text(face="bold",size=14),axis.text.y=element_text(face="bold",size=14),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,2,0,0),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),
     legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "grey30"),
     legend.position=c(0.75,0.85),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),legend.text=element_text(size=12),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
tmpmlt11f
#hmm, b/c the axes scale are so different, it might be confusing to put scatters next to each other as if they were direct comparisons. What if I put all the years in one plot, 
#110822 - trying same figure with MJJ info for 2011.
#note scale_y_continuous(limits=c(-3,0.5),breaks=seq(-3,0.5,0.5)) +      scale_x_continuous(limits=c(-8,18),breaks=seq(-5,15,5)) for 2021.
#    scale_y_continuous(limits=c(-2.05,1.75),breaks=seq(-2,1.75,0.5)) + scale_x_continuous(limits=c(-6,2.5),breaks=seq(-5,15,5)) for 2011.
# yeah this is better but let's just put it in supplemental
# y-axis matches 2021 data but x-axis is substantially compressed
tmpmlt11f_mjj <- 
ggplot(data=zpsC_mjj11,aes(x=pAnom3MA,y=nSWEloss3MA))+
     geom_point(size=3,color="black") + 
     geom_smooth(data=zpsC_mjj11,aes(x=pAnom3MA,y=nSWEloss3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)+
     labs(title=bquote(bold("(a)")~" SWE percent loss relationship to 2011 daily temperature anomalies"), x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)")+
     scale_y_continuous(limits=c(-3.5,3.5),breaks=seq(-3.5,3.5,0.5)) + 
     scale_x_continuous(limits=c(-6,11),breaks=seq(-5,15,2.5)) +
     theme(panel.background=element_blank(), axis.text.x=element_text(face="bold",size=14),axis.text.y=element_text(face="bold",size=14),axis.title=element_text(size=15),axis.title.y=element_text(margin=unit(c(0,2,0,0),"mm")),plot.title=element_text(size=15), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),
     legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "grey30"),
     legend.position=c(0.75,0.85),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),legend.text=element_text(size=12),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
tmpmlt11f_mjj
#exported as ED_Fig5a at 700x700, on 072523
summary(lm(data=zpsC_amj11,nSWEloss3MA~pAnom3MA))
summary(lm(data=zpsC_mjj11,nSWEloss3MA~pAnom3MA))

#AMJ plot of same for 2015
tmpmlt15f <- 
ggplot(data=zpsC_amj15,aes(x=pAnom3MA,y=nSWEloss3MA))+
     geom_point(size=3,color="black") + 
     geom_smooth(data=zpsC_amj15,aes(x=pAnom3MA,y=nSWEloss3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)+
     labs(title=bquote(bold("(b)")~" SWE percent loss relationship to 2015 daily temperature anomalies"), x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)")+
     scale_y_continuous(limits=c(-3.5,3.5),breaks=seq(-3.5,3.5,0.5)) +
     scale_x_continuous(limits=c(-6,11),breaks=seq(-5,15,2.5)) +
     theme(panel.background=element_blank(), axis.text.x=element_text(face="bold",size=14),axis.text.y=element_text(face="bold",size=14),axis.title=element_text(size=15),axis.title.y=element_text(margin=unit(c(0,2,0,0),"mm")),plot.title=element_text(size=15), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),
     legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "grey30"),
     legend.position=c(0.75,0.85),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),legend.text=element_text(size=12),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
#exported as ED_Fig5b at 700x700, on 072523
tmpmlt15f
summary(lm(data=zpsC_amj15,nSWEloss3MA~pAnom3MA))

#061623 - making a scatter of pMeanTemp3MA vs SWE_loss_areaadjusted_3MA in the same style as the above
#doing it but for all years in a single scatter, melt side only.
zpsC_master <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_tm_swe_Master.csv",header=T)
#parse out the melt curves
zpsC_melts <- subset(zpsC_master, zpsC_master$Curve=="DEC")
zpsC_meltsto98 <- subset(zpsC_master, Curve=="DEC" & nSWE >= 0.02)

library(ggplot2)
library(RColorBrewer)

#build plot of all years. Figure 3a as of summer 2023
tmpaar <- 
ggplot(data=zpsC_meltsto98,aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA,group=YearGrouping,color=factor(YearGrouping,labels=c("2011 (Strong La Ni\u00f1a)","2021","El Ni\u00f1o years","La Ni\u00f1a years","ENSO neutral years"))))+
     geom_point(size=3,alpha=0.75) + 
     geom_point(data=subset(zpsC_meltsto98,zpsC_meltsto98$pAnom3MA>5),aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA),color="black",size=3,alpha=0.5)+
     scale_y_continuous(limits=c(-120,20),breaks=seq(-120,20,20)) +
     scale_x_continuous(limits=c(-5,26),breaks=seq(-5,25,5)) +
     labs(title=bquote(bold("(a)")~" SWE loss rate and temperature over the melting season"), x="Daily mean temperature (\u00b0C; 3-day moving average)",y="Rate of Daily SWE change (mm/day; 3-day moving average)") + 
     scale_color_manual(name="Years",breaks=c("2021","2011 (Strong La Ni\u00f1a)","El Ni\u00f1o years","ENSO neutral years","La Ni\u00f1a years"),values=c("2021"="slateblue2","2011 (Strong La Ni\u00f1a)"="slateblue2","ENSO neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) + theme(panel.background=element_blank(), legend.position=c(0.25,0.3),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))

tmpaar

+geom_point(data=subset(zpsC_meltsto98,zpsC_meltsto98$pAnom3MA>5),aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA),color="black",size=6)+

predict(gamtest)


#export as 700x700
#finalized on 061923 - looks great.

#on 072223 - trying to add geom_smooth line and calculate slope and stats
par(mfrow=c(2,2))
plot(lm(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA))
test <- subset(zpsC_meltsto98,DayType=="Normal Days")
plot(lm(data=test,SWE_loss_areaadjusted_3MA~pMeanTemp3MA))
library(skedastic)
library(lmtest)
bptest(lm(data=test,SWE_loss_areaadjusted_3MA~pMeanTemp3MA))
white(lm(data=test,SWE_loss_areaadjusted_3MA~pMeanTemp3MA))
#there is some heteroscedasticity, so I can use the same approach with HC3 as in previous linear models
library(estimatr)
rate_temp_model <- lm_robust(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA,se_type="HC3")
#or with the sandwich package, which generates identical results:
library(sandwich)
hcse <- sqrt(diag(vcovHC(lm(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA), type = "HC3")))

x1cseq <- seq(min(na.omit(zpsC_meltsto98$pMeanTemp3MA)),max(na.omit(zpsC_meltsto98$pMeanTemp3MA)),length.out=2067)
predict.lm(lm(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA))
predvals <- predict.lm(lm(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA),newdata=x1cseq)
predline <- data.frame(pMeanTemp3MA=x1cseq,y=predict(lm(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA),newdata=x1cseq))

predline <- data.frame(actual=x1cseq, predicted=predict(lm(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA)))

predline <- data.frame(pMeanTemp3MA=x1cseq,y=predict.lm(lm(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~pMeanTemp3MA)))
predline$y <- (predline$x * -2.486223) + 2.311694

tmpaar <- ggplot()+
     geom_point(data=zpsC_meltsto98,aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA,group=YearGrouping,color=factor(YearGrouping,labels=c("2011 (Strong La Ni\u00f1a)","2021","El Ni\u00f1o years","La Ni\u00f1a years","ENSO neutral years"))),size=3,alpha=0.75) + 
     geom_point(data=subset(zpsC_meltsto98,zpsC_meltsto98$DayType=="Heat Dome Days"),aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA),color="black",size=6)+
     geom_smooth(data=predline,aes(x=x1cseq,y=y),method="lm",se=F,color="black",linetype=2)+
     scale_y_continuous(limits=c(-120,20),breaks=seq(-120,20,20)) +
     scale_x_continuous(limits=c(-5,26),breaks=seq(-5,25,5)) +
     labs(title=bquote(bold("(a)")~" SWE loss rate and temperature over the melting season"), x="Daily mean temperature (\u00b0C; 3-day moving average)",y="Rate of Daily SWE change (mm/day; 3-day moving average)") + 
     scale_color_manual(name="Years",breaks=c("2021","2011 (Strong La Ni\u00f1a)","El Ni\u00f1o years","ENSO neutral years","La Ni\u00f1a years"),values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) + theme(panel.background=element_blank(), legend.position=c(0.25,0.3),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))
#looks great, exporting this as the new tmpaar (700x700)

#you can see in this unused plot below that the Std err interval is small even when showing subgroups, so I am going to forgo including it in the nice version (above)
ggplot(data=zpsC_meltsto98,aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA,group=YearGrouping,color=factor(YearGrouping,labels=c("2011 (Strong La Ni\u00f1a)","2021","El Ni\u00f1o years","La Ni\u00f1a years","ENSO neutral years"))),)+
     geom_point(size=3,alpha=0.75) + 
     geom_point(data=subset(zpsC_meltsto98,zpsC_meltsto98$DayType=="Heat Dome Days"),aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA),color="black",size=6)+
     geom_smooth(method="lm",se=T)+
     scale_y_continuous(limits=c(-120,20),breaks=seq(-120,20,20)) +
     scale_x_continuous(limits=c(-5,26),breaks=seq(-5,25,5)) +
     labs(title=bquote(bold("(a)")~" SWE loss rate and temperature over the melting season"), x="Daily mean temperature (\u00b0C; 3-day moving average)",y="Rate of Daily SWE change (mm/day; 3-day moving average)") + 
     scale_color_manual(name="Years",breaks=c("2021","2011 (Strong La Ni\u00f1a)","El Ni\u00f1o years","ENSO neutral years","La Ni\u00f1a years"),values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) + theme(panel.background=element_blank(), legend.position=c(0.25,0.3),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))


#build plot of all years. Figure 3b as of fall 2023
anomnswe <- 
ggplot(data=zpsC_AMJ,aes(x=pAnom3MA,y=nSWEloss3MA,group=YearGrouping,color=factor(YearGrouping,labels=c("2011 (Strong La Ni\u00f1a)","2021","El Ni\u00f1o years","La Ni\u00f1a years","ENSO neutral years"))))+
     geom_point(size=3,alpha=0.75) + 
     geom_point(data=subset(zpsC_AMJ,zpsC_AMJ$DayType=="Heat Dome Days"),aes(x=pAnom3MA,y=nSWEloss3MA),color="black",size=6)+
     scale_y_continuous(limits=c(-5,4),breaks=seq(-5,4,1)) +
     scale_x_continuous(limits=c(-9,15),breaks=seq(-9,15,3)) +
     labs(title=bquote(bold("(b)")~" SWE percent loss rate and April, May, June daily temperature anomalies"), x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)") + 
     scale_color_manual(name="Years",breaks=c("2021","2011 (Strong La Ni\u00f1a)","El Ni\u00f1o years","ENSO neutral years","La Ni\u00f1a years"),values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) + theme(panel.background=element_blank(), legend.position=c(0.8,0.8),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))

anomnswe

#export as 700x700
#on 092023 - looks great for now

#on 092023 - trying to add geom_smooth line and calculate slope and stats
par(mfrow=c(2,2))
plot(lm(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA))
test <- subset(zpsC_AMJ,DayType=="Normal Days")
plot(lm(data=test,nSWEloss3MA~pAnom3MA))
library(skedastic)
library(lmtest)
bptest(lm(data=test,nSWEloss3MA~pAnom3MA))
white(lm(data=test,nSWEloss3MA~pAnom3MA))
#there is some heteroscedasticity, so I can use the same approach with HC3 as in previous linear models
library(estimatr)
nswe_tanom_model <- lm_robust(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA,se_type="HC3")
#or with the sandwich package, which generates identical results:
library(sandwich)
hcse <- sqrt(diag(vcovHC(lm(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA), type = "HC3")))

x1cseq <- seq(min(na.omit(zpsC_AMJ$pAnom3MA)),max(na.omit(zpsC_AMJ$pAnom3MA)),length.out=1638)
predict.lm(lm(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA))
predvals <- predict.lm(lm(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA),newdata=x1cseq)
predline <- data.frame(pAnom3MA=x1cseq,y=predict(lm(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA),newdata=x1cseq))

predline <- data.frame(actual=x1cseq, predicted=predict(lm(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA)))

predline <- data.frame(pAnom3MA=x1cseq,y=predict.lm(lm(data=zpsC_AMJ,nSWEloss3MA~pAnom3MA)))
predline$y <- (predline$pAnom3MA * -0.1714019) - 0.8450562

anomnswe <- ggplot()+
     geom_point(data=zpsC_AMJ,aes(x=pAnom3MA,y=nSWEloss3MA,group=YearGrouping,color=factor(YearGrouping,labels=c("2011 (Strong La Ni\u00f1a)","2021","El Ni\u00f1o years","La Ni\u00f1a years","ENSO neutral years"))),size=3,alpha=0.75) + 
     geom_point(data=subset(zpsC_AMJ,zpsC_AMJ$DayType=="Heat Dome Days"),aes(x=pAnom3MA,y=nSWEloss3MA),color="black",size=6)+
     geom_smooth(data=predline,aes(x=x1cseq,y=y),method="lm",se=F,color="black",linetype=2)+
     scale_y_continuous(limits=c(-5,4),breaks=seq(-5,4,1)) +
     scale_x_continuous(limits=c(-9,15),breaks=seq(-9,15,3)) +
     labs(title=bquote(bold("(b)")~" SWE percent loss rate and April, May, June daily temperature anomalies"), x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)") + 
     scale_color_manual(name="Years",breaks=c("2021","2011 (Strong La Ni\u00f1a)","El Ni\u00f1o years","ENSO neutral years","La Ni\u00f1a years"),values=c("2021"="black","2011 (Strong La Ni\u00f1a)"="blue","ENSO neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) + theme(panel.background=element_blank(), legend.position=c(0.8,0.8),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))
#looks great, exporting this as the new Fig 3b, anomnswer (700x700)

ggplot(data=zpsC_amj21,aes(x=pAnom3MA,y=nSWEloss3MA,color=DayType))+
     geom_point(size=3) + 
     geom_smooth(data=zpsC_amj21,aes(x=pAnom3MA,y=nSWEloss3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)
 
     theme(panel.background=element_blank(), axis.text.x=element_text(face="bold",size=14),axis.text.y=element_text(face="bold",size=14),axis.title=element_text(size=16),axis.title.y=element_text(margin=unit(c(0,2,0,0),"mm")),plot.title=element_text(size=18), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y = element_line(colour = 'black', size=0.5, linetype='solid'),
     legend.title = element_blank(),
        legend.spacing.y = unit(0, "mm"), 
        legend.background = element_blank(),
        legend.box.background = element_rect(colour = "grey30"),
     legend.position=c(0.75,0.85),legend.key=element_rect(fill="white"),legend.key.width=unit(1,"cm"),legend.text=element_text(size=12),
     panel.border = element_rect(colour = "black", fill=NA, size=2))

     geom_smooth(data=zpsC_amj21,aes(x=pAnom3MA,y=nSWEloss3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)+     


#as of 081922, this is the polished version of the figure - looks solid
#summary stats on the geom_smooth portion:
summary(lm(data=zpsC_amj21,nSWEloss3MA~pAnom3MA))

ggplot(data=zpsC_amj21,aes(x=pAnom3MA,y=nSWEloss3MA,color=DayType))+
     geom_point(size=3) + 
     geom_smooth(data=zpsC_amj21,aes(x=pAnom3MA,y=nSWEloss3MA),method=lm,color="black",fill="grey20",alpha=0.2,size=0.5)




#PRISM figure being fine-tuned on 111722; readjusted and exported on 072423
pDegDayPlus5Canomslm <- ggplot(pzpsC5Cbyyr,aes(x=Year,y=pDegDayPlus5C_30,label=Year),na.rm=F) +
   geom_smooth(data=as.data.frame(pzpsC5Csince93),aes(x=Year,y=pDegDayPlus5C_30),method="lm",
   color="black",fill="grey20",alpha=0.2,size=0.5)+
   geom_point(aes(fill=ENSOoni),size=4.5,shape=21,color="black")+
   geom_text(aes(label=ifelse(pDegDayPlus5C_30>125,as.character(Year),'')),hjust=1,vjust=1,nudge_y=-3,nudge_x=0,size=4.5)+
   annotate("text",x=2012.3,y=6.5,label="2011",size=4.5)+
   labs(x="Year",y="Sum of daily anomalies \u2265 5\u00b0C",title=bquote(bold("(a)")~" Summed daily anomalies \u2265 5\u00b0C during AMJ period annually"))+
   scale_x_continuous(expand=c(0,1.5,0,1.5),limits=c(1993,2021),breaks=c(1993,1997,2001,2005,2009,2013,2017,2021))+
   scale_y_continuous(limits=c(0,200),breaks=c(0,50,100,150,200),oob=rescale_none)+
   scale_fill_continuous_divergingx(name="ENSO class",palette="RdBu",rev=TRUE,breaks=c(2,1.5,1,0.5,0,-0.5,-1,-1.5),mid=0,labels=c("\n\nVery Strong\nEl Ni\u00f1o","\n\nStrong\nEl Ni\u00f1o","\n\nModerate\nEl Ni\u00f1o","\n\nWeak\nEl Ni\u00f1o","Neutral","Weak\nLa Ni\u00f1a\n\n","Moderate\nLa Ni\u00f1a\n\n","Strong La\nNi\u00f1a\n\n"),na.value="grey50")+
   theme(panel.background=element_blank(),axis.text.x=element_text(face="bold",size=16),axis.text.y=element_text(face="bold",size=16),axis.title=element_text(size=16),plot.title=element_text(size=16), axis.line.x = element_line(colour = 'black', size=0.5, linetype='solid'), axis.line.y =element_line(colour='black', size=0.5, linetype='solid'),
        legend.spacing.y = unit(5, "mm"), 
        legend.background = element_rect(fill="white"),
        legend.position="right",legend.key=element_rect(fill="white"),legend.key.width=unit(.75,"cm"),legend.key.height=unit(2,"cm"),legend.text=element_text(size=12),
     panel.border = element_rect(colour = "black", fill=NA, size=2))
pDegDayPlus5Canomslm
#quick and dirty 755 (width) by 700 pixels

#to export:
png("Fig4a.png",width=2500,height=2000,res=300)
png("Fig4a.png",width=5000,height=4000,res=600)
pDegDayPlus5Canomslm
dev.off()
#exported to working directory

##110922 - making a series of ~10 stations to include in supplemental

#062923 - sublimation analysis
#generate a column of sublimation in the persistent snow zone per SNODAS.
# both types?
#first task is using the bash scripts to extract the sublimation rasters and convert to netcdf
#calculating sublimation
library(sp)
library(raster)
library(ncdf4)
library(ggplot2)
setwd("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\nc")
# when finished, navigate back to setwd(setwd("C:/Users/luke.reyes/OneDrive - Washington State University (email.wsu.edu)/Snow/scratch")
raster("SWE_snodas_20210628_sub.nc")

#there is an odd issue in the sublimation rasters - there are a ton of negative values.
#070623 - I reached out to NSIDC to see what they think. They agree it is odd and will be in touch after looking into it more closely. The below code generates some graphs that were used to show them what the issue is.
library(maps)
#map of stations
states = map_data("state")
#subset of just the region of OR,WA,CA (and a smidge of Nevada for completeness'sake) I want
west3 = subset(states,region %in% c("oregon","washington","california","nevada","idaho","montana"))
#make a base polygon foundation of the area of interest

#example snowpack sublimation plot
rast41 <- as.data.frame(raster("SUBS_snodas_20210401_sub.nc"),xy=TRUE)
ggplot(data=west3) + geom_raster(data = rast41,mapping=aes(x=x,y=y,fill=Sublimation_From_Snowpack))+ geom_polygon(aes(x=long,y=lat,group=group),fill=NA, color="black") + coord_fixed(xlim = c(-124.35, -116.67),  ylim = c(42.2, 48.75),ratio = 1.3)+  scale_fill_gradientn(colours= rev(terrain.colors(10)), name='Snowpack Sublimation')+labs(title="April 1st, 2006",x="Longitude",y="Latitude")+theme_bw()
#example sublimation of blowing snow plot
rast41 <- as.data.frame(raster("SUBB_snodas_20210401_sub.nc"),xy=TRUE)
ggplot(data=west3) + geom_raster(data = rast41,mapping=aes(x=x,y=y,fill=Sublimation_From_Blowing_Snow))+ geom_polygon(aes(x=long,y=lat,group=group),fill=NA, color="black") + coord_fixed(xlim = c(-124.35, -116.67),  ylim = c(42.2, 48.75),ratio = 1.3)+  scale_fill_gradientn(colours= rev(terrain.colors(10)), name='Blowing Snow Sublimation')+labs(title="April 1st, 2021",x="Longitude",y="Latitude")+theme_bw()

rast41 <- as.data.frame(raster("SUBS_snodas_20210601_sub.nc"),xy=TRUE)
ggplot(data=west3) + geom_raster(data = as.data.frame(raster("SUBS_snodas_20210601_sub.nc"),xy=TRUE),mapping=aes(x=x,y=y,fill=Sublimation_From_Snowpack))+ geom_polygon(aes(x=long,y=lat,group=group),fill=NA, color="black") + coord_fixed(xlim = c(-124.35, -116.67),  ylim = c(42.2, 48.75),ratio = 1.3)+  scale_fill_gradientn(colours= rev(terrain.colors(10)), name='Snowpack Sublimation')+labs(title="April 1st, 2006",x="Longitude",y="Latitude")+theme_bw()

cellStats(raster("SUBS_snodas_20210401_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210402_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210403_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210404_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210405_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210406_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210407_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210408_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210409_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210410_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210411_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210412_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210413_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210414_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210415_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210416_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210417_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210418_sub.nc"),max)
cellStats(raster("SUBS_snodas_20210419_sub.nc"),max)

#modify this code in the first and last lines to customize for year (ie Lswe and write.csv)
Lswe <- list.files("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\SNODAS_NetCDF\\2023_SublimationProject\\nc", pattern="SUBS_snodas_2021")
RasterID <- c()
SubSnow <- c()
for (i in 1:length(Lswe)){
    RasterID[i] <- substr(Lswe[i],12,19)
    loopras <- raster(Lswe[i])
    loopras[loopras[]<5] <- NA
    loopras <- loopras/loopras
    SCA_5mm[i] <- extract(loopras,zpsC_shp,fun=sum,na.rm=TRUE)
    }
SCA_pct <- (SCA_5mm/51235)*100
zpsC_SCA5_csv <- write.csv(data.frame(RasterID, SCA_5mm, SCA_pct), "C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\zpsC_SCA5_21.csv")

#This above loop worked great. I manually appended everything in Excel once I had the individual year csvs. I also interpolated, in the combined table, the missing dates (reference ExtractionLog.xlsx in SNODASdata folder and the readme.txt in the ZS_csvs folder)

#092023 - gam test
library(gam)
gamtest <- gam(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~s(pMeanTemp3MA))
#ignore above and use the mgcv tool below
library(mgcv)
gamtest <- mgcv::gam(data=zpsC_meltsto98,SWE_loss_areaadjusted_3MA~s(pMeanTemp3MA))
summary(gamtest)
summary(rate_temp_model)
plot(gamtest)
#gam has a better R2, slightly, than the linear model
#first pass at a regraphed 3a to colorize all heatwave points
ggplot(data=zpsC_meltsto98,aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA,group=YearGrouping,color=factor(YearGrouping,labels=c("2011 (Strong La Ni\u00f1a)","2021","El Ni\u00f1o years","La Ni\u00f1a years","ENSO neutral years"))))+
+     geom_point(size=3,alpha=0.75) + 
+     geom_point(data=subset(zpsC_meltsto98,zpsC_meltsto98$pAnom3MA>5),aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA),color="black",size=3,alpha=0.5)+
+     scale_y_continuous(limits=c(-120,20),breaks=seq(-120,20,20)) +
+     scale_x_continuous(limits=c(-5,26),breaks=seq(-5,25,5)) +
+     labs(title=bquote(bold("(a)")~" SWE loss rate and temperature over the melting season"), x="Daily mean temperature (\u00b0C; 3-day moving average)",y="Rate of Daily SWE change (mm/day; 3-day moving average)") + 
+     scale_color_manual(name="Years",breaks=c("2021","2011 (Strong La Ni\u00f1a)","El Ni\u00f1o years","ENSO neutral years","La Ni\u00f1a years"),values=c("2021"="slateblue2","2011 (Strong La Ni\u00f1a)"="slateblue2","ENSO neutral years"="grey50","La Ni\u00f1a years"="slateblue2","El Ni\u00f1o years"="indianred2")) + theme(panel.background=element_blank(), legend.position=c(0.25,0.3),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))
#what is the slope and R2 of just the heatwave points?
bptest(lm(data=subset(zpsC_meltsto98,zpsC_meltsto98$pAnom3MA>5),SWE_loss_areaadjusted_3MA~pMeanTemp3MA))
#there is some heteroscedasticity, so using lm_robust again
library(estimatr)
hwrate_temp_model <- lm_robust(data=subset(zpsC_meltsto98,zpsC_meltsto98$pAnom3MA>5),SWE_loss_areaadjusted_3MA~pMeanTemp3MA,se_type="HC3")
summary(hwrate_temp_model)

#improved graph to simplify colors and add trendlines
zpsC_meltsto98$YearGroupingSimple <- zpsC_meltsto98$YearGrouping
zpsC_meltsto98$YearGroupingSimple <- replace(zpsC_meltsto98$YearGroupingSimple,zpsC_meltsto98$YearGroupingSimple=="2011","LaNina")
zpsC_meltsto98$YearGroupingSimple <- replace(zpsC_meltsto98$YearGroupingSimple,zpsC_meltsto98$YearGroupingSimple=="2021","LaNina")
levels(zpsC_meltsto98$YearGroupingSimple)
zpsC_meltsto98$YearGroupingSimple[zpsC_meltsto98$pAnom3MA>=5] <- "HeatwaveDays"
zpsC_meltsto98$YearGroupingSimple <- factor(zpsC_meltsto98$YearGroupingSimple, levels=c('LaNina', 'Neutral', 'ElNino', 'HeatwaveDays'))

xgamseq <- seq(min(na.omit(zpsC_meltsto98$pMeanTemp3MA)),max(na.omit(zpsC_meltsto98$pMeanTemp3MA)),length.out=2067)
xgamseq <- data.frame(pMeanTemp3MA=xgamseq)
predict(gamtest,xgamseq)
gampredline <- data.frame(x=xgamseq,y=predict(gamtest,xgamseq))
linpredline <- data.frame(x=xgamseq,y=predict(rate_temp_model,xgamseq))
hwpredline <- data.frame(pMeanTemp3MA=seq(min(na.omit(zpsC_meltsto98$pMeanTemp3MA)),max(na.omit(zpsC_meltsto98$pMeanTemp3MA)),length.out=220))
hwpredline$y <- (hwpredline$pMeanTemp3MA* -3.516167) + 16.68117
"     geom_line(data=hwpredline,aes(x=pMeanTemp3MA,y=y),color="black",linetype=1)+"
#actually the hwpredline does not look very useful. it is not going to be in the plot

tmpaar <- ggplot()+
     geom_point(data=zpsC_meltsto98,aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA,group=YearGroupingSimple,color=factor(YearGroupingSimple,labels=c("La Ni\u00f1a","ENSO neutral","El Ni\u00f1o","Heatwave days\n(all years)"))),size=2.5,alpha=0.6) + 
     geom_point(data=subset(zpsC_meltsto98,zpsC_meltsto98$pAnom3MA>5),aes(x=pMeanTemp3MA,y=SWE_loss_areaadjusted_3MA),color="black",size=2.5,alpha=0.6) +
     geom_line(data=linpredline,aes(x=pMeanTemp3MA,y=y,linetype="Linear model fit"),color="grey75",linewidth=1.1)+
     geom_line(data=gampredline,aes(x=pMeanTemp3MA,y=y,linetype="GAM fit"),color="black",linewidth=1.1)+
     scale_y_continuous(limits=c(-120,20),breaks=seq(-120,20,20)) +
     scale_x_continuous(limits=c(-5,26),breaks=seq(-5,25,5)) +
     labs(title=bquote(bold("(a)")~" SWE loss rate and temperature over the melting season"), x="Daily mean temperature (\u00b0C; 3-day moving average)",y=bquote("Rate of Daily SWE change (mm"~day^-1*"; 3-day moving average)")) + 
     scale_color_manual(name=NULL,breaks=c("La Ni\u00f1a","ENSO neutral","El Ni\u00f1o","Heatwave days\n(all years)"),values=c("El Ni\u00f1o"="indianred2","ENSO neutral"="grey40","La Ni\u00f1a"="slateblue2","Heatwave days\n(all years)"="black"),guide=guide_legend(override.aes=list(linetype=0))) + 
     scale_linetype_manual(name=NULL,breaks=c("Linear model fit","GAM fit"),values=c("Linear model fit"="54","GAM fit"="12"),guide=guide_legend(override.aes=list(colour=c("grey75","black"))))+
     theme(panel.background=element_blank(), legend.position=c(0.18,0.24),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA,size=1),legend.key.size = unit(0.75, 'cm'))

ggsave(filename="Fig3a.png",path = "C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\Drafts\\SubmissionCopies\\AcceptInPrinciple_October2023", width=15, height=15, units="cm", device='png', dpi=600)

zpsC_AMJ$YearGroupingSimple <- zpsC_AMJ$YearGrouping
zpsC_AMJ$YearGroupingSimple <- replace(zpsC_AMJ$YearGroupingSimple,zpsC_AMJ$YearGroupingSimple=="2011","LaNina")
zpsC_AMJ$YearGroupingSimple <- replace(zpsC_AMJ$YearGroupingSimple,zpsC_AMJ$YearGroupingSimple=="2021","LaNina")
levels(zpsC_AMJ$YearGroupingSimple)
zpsC_AMJ$YearGroupingSimple[zpsC_AMJ$pAnom3MA>=5] <- "HeatwaveDays"
zpsC_AMJ$YearGroupingSimple <- factor(zpsC_AMJ$YearGroupingSimple, levels=c('LaNina', 'Neutral', 'ElNino', 'HeatwaveDays'))

anomnswe <- ggplot()+
     geom_point(data=zpsC_AMJ,aes(x=pAnom3MA,y=nSWEloss3MA,group=YearGroupingSimple,color=factor(YearGroupingSimple,labels=c("La Ni\u00f1a","ENSO neutral","El Ni\u00f1o","Heatwave days\n(all years)"))),size=2.5,alpha=0.6) + 
     geom_point(data=subset(zpsC_AMJ,zpsC_AMJ$pAnom3MA>5),aes(x=pAnom3MA,y=nSWEloss3MA),color="black",size=2.5,alpha=0.6) +     
     geom_smooth(data=predline,aes(x=x1cseq,y=y),method="lm",se=F,color="black",linetype=2)+
     scale_y_continuous(limits=c(-5,4),breaks=seq(-5,4,1)) +
     scale_x_continuous(limits=c(-9,15),breaks=seq(-9,15,3)) +
     labs(title=bquote(bold("(b)")~" SWE percent loss and April-June daily temperature anomalies"), x="Daily temperature anomaly (\u00b0C; 3-day moving average)",y="Percent change in daily SWE (3-day moving average)") + 
     scale_color_manual(name=NULL,breaks=c("La Ni\u00f1a","ENSO neutral","El Ni\u00f1o","Heatwave days\n(all years)"),values=c("El Ni\u00f1o"="indianred2","ENSO neutral"="grey40","La Ni\u00f1a"="slateblue2","Heatwave days\n(all years)"="black")) + theme(panel.background=element_blank(), legend.position=c(0.85,0.85),legend.key=element_rect(fill="white"),panel.border = element_rect(colour = "black", fill=NA, size=1))
ggsave(filename="Fig3b.png",path = "C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\Drafts\\SubmissionCopies\\AcceptInPrinciple_October2023", width=15, height=15, units="cm", device='png', dpi=600)


#multiple linear regression test
library(car)
scatter3d(sllmd$PeakSWE,sllmd$JDay05SCA,sllmd$pDegDayPlus5C_30,point.col="black",surface=TRUE)
sllmd <- read.csv("C:\\Users\\luke.reyes\\OneDrive - Washington State University (email.wsu.edu)\\Snow\\ZS_csvs\\SeasonLengthModelData.csv")
sllmdt <- sllmd[,c("PeakSWE","pDegDayPlus5C_30","JDay05SCA")]
mahalanobis(sllmdt,colMeans(sllmdt),cov(sllmdt))
sllmdt$mahal <- mahalanobis(sllmdt,colMeans(sllmdt),cov(sllmdt))
sllmdt$p <- pchisq(sllmdt$mahal,df=2,lower.tail=FALSE)
sllmdt
sl.lm <- lm(data=sllmd, JDay05SCA~pDegDayPlus5C_30 + PeakSWE)
summary(sl.lm)
library(rgl)
avPlot3d(sl.lm,"PeakSWE","pDegDayPlus5C_30",id=TRUE)

library(scatterplot3d)
s3d <- scatterplot3d(sllmd$PeakSWE,sllmd$pDegDayPlus5C_30,sllmd$JDay05SCA, type = "h", color = "black", angle=130, pch = 16)
test <- lm(sllmd$JDay05SCA~sllmd$PeakSWE+sllmd$pDegDayPlus5C_30)
s3d$plane3d(test)

s3d <- scatterplot3d(sllmd$PeakSWE,sllmd$pDegDayPlus5C_30,sllmd$JDay05SCA, type = "p", color = "grey45", main="Snow cover loss date predicted by\n peak SWE and AMJ heatwaves",xlab="Peak SWE (mm)",ylab="Sum of AMJ daily anomalies \u2265 5\u00b0C",zlab="Julian day of 95% snow cover loss",grid=TRUE, box=FALSE, angle=50, pch = 19)
orig     <- s3d$xyz.convert(sllmd$PeakSWE, sllmd$pDegDayPlus5C_30, sllmd$JDay05SCA)
plane    <- s3d$xyz.convert(sllmd$PeakSWE, sllmd$pDegDayPlus5C_30, fitted(test))
i.negpos <- 1 + (resid(test) > 0) # which residuals are above the plane?
segments(orig$x, orig$y, plane$x, plane$y, col = "red", lty = c(2, 1)[i.negpos], lwd = 1.5)
s3d$plane3d(test, draw_polygon = TRUE, draw_lines = TRUE, 
                  polygon_args = list(col = rgb(0.6,0.6,0.6,0.2)))
wh <- resid(test) > 0
segments(orig$x[wh], orig$y[wh], plane$x[wh], plane$y[wh], col = "red", lty = 1, lwd = 1.5)
s3d$points3d(sllmd$PeakSWE[wh], sllmd$pDegDayPlus5C_30[wh], sllmd$JDay05SCA[wh], pch = 19)
#scatterplot generated following guidance at https://stackoverflow.com/questions/47344850/scatterplot3d-regression-plane-with-residuals
#to export:
png("Reyes_EDfig8.png",width=1600,height=1600,res=300)
png("Reyes_Sfig8.png",width=3200,height=3200,res=600)
#generate graph following display commands immediately above
dev.off()
#exported to working directory
